shell(七)

102 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第25天,点击查看活动详情

显示命令的执行结果
echo `date`

输出结果:

Wed Sep 1 11:45:33 CST 2021
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 文件不存在