Aliens

Shell中的常用语法

April 3, 2021

获取文件名/文件扩展名

1
2
3
4
5
6
7
8
9
~% FILE="example.tar.gz"
~% echo "${FILE%%.*}"
example
~% echo "${FILE%.*}"
example.tar
~% echo "${FILE#*.}"
tar.gz
~% echo "${FILE##*.}"
gz

https://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash

去除字符串的前缀/后缀

有一个字符串为hello-world, 现在希望去除前缀hell和后缀ld, 得到新的字符串o-wor

1
2
3
string="hello-world"
prefix="hell"
suffix="ld"

方法如下:

1
2
3
4
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor

https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash

手动向stderr输出

1
>&2 echo "error"

https://stackoverflow.com/questions/2990414/echo-that-outputs-to-stderr

创建临时文件夹

1
2
3
4
5
6
7
# 创建临时文件夹
$ mktemp -d
/tmp/tmp.vwjuFmclTR

# 创建临时文件夹,并指定模板
$ mktemp -d -t test-XXXXX
/tmp/test-4kceq

https://code-maven.com/create-temporary-directory-on-linux-using-bash

判断字符串是否为空

正确做法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/sh

STRING=

if [ -z "$STRING" ]; then
    echo "STRING is empty"
fi

if [ -n "$STRING" ]; then
    echo "STRING is not empty"
fi
---------------
输出正确结果:

root@james-desktop:~# ./zerostring.sh
STRING is empty

错误做法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/sh

STRING=

if [ -z $STRING ]; then
    echo "STRING is empty"
fi

if [ -n $STRING ]; then
    echo "STRING is not empty"
fi
---------------------
输出错误结果:

root@james-desktop:~# ./zerostring.sh
STRING is empty
STRING is not empty

https://www.cnblogs.com/cute/archive/2011/08/26/2154137.html

更多用法: https://www.cyberciti.biz/faq/unix-linux-bash-script-check-if-variable-is-empty/