[shell(4) | 青训营笔记]

128 阅读3分钟

printf命令

printf命令用于格式化输出,类似于C/C++中的printf函数。

默认不会在字符串末尾添加换行符。

命令格式:

printf format-string \[arguments...]

用法示例
脚本内容:

printf "%10d.\n" 123  # 占10位,右对齐
printf "%-10.2f.\n" 123.123321  # 占10位,保留2位小数,左对齐
printf "My name is %s\n" "yxc"  # 格式化输出字符串
printf "%d \* %d = %d\n"  2 3 `expr 2 \* 3` # 表达式的值作为参数

输出结果:

       123.

123.12    .
My name is yxc
2 \* 3 = 6

test命令与判断符号[]

逻辑运算符&&和||

&& 表示与,|| 表示或
二者具有短路原则:
expr1 && expr2:当expr1为假时,直接忽略expr2
expr1 || expr2:当expr1为真时,直接忽略expr2
表达式的exit code为0,表示真;为非零,表示假。(与C/C++中的定义相反)

test命令

在命令行中输入man test,可以查看test命令的用法。

test命令用于判断文件类型,以及对变量做比较。

test命令用exit code返回结果,而不是使用stdout。0表示真,非0表示假。

例如:

test 2 -lt 3  # 为真,返回值为0
echo $?  # 输出上个命令的返回值,输出0
acs@9e0ebfcd82d7:~$ ls  # 列出当前目录下的所有文件
homework  output.txt  test.sh  tmp
acs\@9e0ebfcd82d7:\~$ test -e test.sh && echo "exist" || echo "Not exist"
exist  # test.sh 文件存在
acs@9e0ebfcd82d7:~$ test -e test2.sh && echo "exist" || echo "Not exist"
Not exist  # testh2.sh 文件不存在

文件类型判断

命令格式:

test -e filename  # 判断文件是否存在
测试参数代表意义
-e文件是否存在
-f是否为文件
-d是否为目录

文件权限判断

命令格式:

test -r filename  # 判断文件是否可读
测试参数代表意义
-r文件是否可读
-w文件是否可写
-x文件是否可执行
-s是否为非空文件

整数间的比较

命令格式:

test $a -eq $b  # a是   否等于b
测试参数代表意义
-eqa是否等于b
-nea是否不等于b
-gta是否大于b
-lta是否小于b
-gea是否大于等于b
-lea是否小于等于b

字符串比较

测试参数代表意义
test -z STRING判断STRING是否为空,如果为空,则返回true
test -n STRING判断STRING是否非空,如果非空,则返回true(-n可以省略)
test str1 == str2判断str1是否等于str2
test str1 != str2判断str1是否不等于str2

多重条件判定

命令格式:

test -r filename -a -x filename
测试参数代表意义
-a两条件是否同时成立
-o两条件是否至少一个成立
!取反。如 test ! -x file,当file不可执行时,返回true
判断符号[]

[]与test用法几乎一模一样,更常用于if语句中。另外[[]]是[]的加强版,支持的特性更多。

例如:

\[ 2 -lt 3 ]  # 为真,返回值为0
echo $?  # 输出上个命令的返回值,输出0
acs@9e0ebfcd82d7:~$ ls  # 列出当前目录下的所有文件
homework  output.txt  test.sh  tmp
acs\@9e0ebfcd82d7:\~$ [ -e test.sh ] && echo "exist" || echo "Not exist"
exist  # test.sh 文件存在
acs@9e0ebfcd82d7:~$ \[ -e test2.sh ] && echo "exist" || echo "Not exist"
Not exist  # testh2.sh 文件不存在

注意:

[]内的每一项都要用空格隔开
中括号内的变量,最好用双引号括起来
中括号内的常数,最好用单或双引号括起来
例如:

name="acwing yxc"
\[ $name == "acwing yxc" ]  # 错误,等价于 [ acwing yxc == "acwing yxc" ],参数太多 [ "$name" == "acwing yxc" ]  # 正确