shell 条件

test命令内的条件为真,则返回退出状态码0

test 5 -eq 15 && echo Yes || echo No

teest  var1     #测试变量是否有值

test -f /etc/resolv.conf && echo "File /etc/resolv.conf found." || echo "File /etc/resolv.conf not found."

test ! -f "$FILE" 

 

if test var == value

if test -f   "$file"           # 双引号把变量括起来,可处理变量里可能存在的空格等特殊字符

if [ condition ] then ... elif condition1 then

...

elif condition2 then

...

else

...

fi

if test $a == "c" ;then echo 'yes'; fi             # 写在一行里

if ls /app >/dev/null ; then echo 'y'; else echo 'n'; fi # 检测命令是否成功     

?命令成功后不是返回0吗?   

echo $?        # 输出上一条命令的退出状态  0表示成功

ls -l /tmp >/dev/null status=$? if test $status -eq 0

if [ -d $HOME ] && [ -f $HOME/abc.txt ]         逻辑运算

数值比较:  -eq  -ge  -gt  -le  -lt  -ne

字符串比较:    s1 = s2       s1 != s2        s1 < s2       s1 > s2        大于小于号要转义:    [ s1 \< s2 ]

     -n s1 长度非0        -z s1 长度为0,空字符串或未定义变量

文件比较:

 

(( a = 2 ** 3 ))

echo $a       # 8

if (( $a ** 2 > 4 )) ; then echo 'y'; else echo 'n'; fi          大于号不用转义      语法有错?

双方括号 支持字符串正则比较

if [[ $str == ab* ]];then....; fi

猜你喜欢

转载自www.cnblogs.com/ts65214/p/12967897.html