shell-1-day
printf 命令
printf 命令的语法:
printf format-string [arguments...]
format-string 为格式控制字符串arguments
参数列表%s %c %d %f 都是格式替代符,%s 输出一个字符串,%d 整型输出,%c 输出一个字符,%f 输出实数,以小数形式输出。和 python 的 print格式替换符一样
test 命令
test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。
#!/bin/bash a=100 b=100 if test $a -eq $b then echo 'two numbers is equal' else echo 'not equal' fi result=$a+$b echo "result is : $result " r2=$[a+b] echo "r2 is : $r2"
two numbers is equal result is : 100+100 r2 is : 200
总结 :Shell 里面的中括号(包括单中括号与双中括号)可用于一些条件的测试:
- 算数比较。用于比较两个数字,相同则返回 true:[ $a == $b ] ps:条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [ $a == $b ]。
- 文件属性测试,比如一个文件是否存在,[ -e $var ], 是否是目录,[ -d $var ]
- 字符串比较, 比如两个字符串是否相同:[ $a = $b ]
- [] 常常可以使用 test 命令来代替
if else
语法格式:
if condition then command1 command2 ... commandN fi
if else-if else 语法格式:
if condition1 then command1 elif condition2 then command2 else commandN fi
for 循环
for var in item1 item2 ... itemN do command1 command2 ... commandN done
[ $a == $b ] |