shell脚本-4

1.test,判断测试

test -z 判断文件是否为空

test -d  判断是否为目录,test -d ./ && echo "yes" || echo "no"的输出为yes;test -d ./aa.txt && echo "yes" || echo "no"的输出为no

test -e  测试文件是否存在.

test -e aa.txt

echo "$?" #输出为0则表示上一个命令正确执行,表示文件存在;输出非0则文件不存在。

或者使用:

test -e aa.txt && echo "yes" || echo "no" #判断文件aa.txt是否存在

test -e 也可以写为[ -e aa.txt ]。该指令与上面的指令相同:[ -e aa.txt ] && echo "yes" || echo "no"

判断数字大小:

[ n1 -eq n2 ]  # 判断是否n1==n2

[ n1 -ne n2 ]  # 判断是否n1!=n2

[ n1 -gt n2 ]  # 判断是否n1>n2

[ n1 -lt n2 ]  # 判断是否n1<n2

[ n1 -ge n2 ]  # 判断是否n1>=n2

[ n1 -le n2 ]  # 判断是否n1<=n2

例如, aa=55,bb=55

[ $aa -eq $bb ] && echo "yes" || echo "no"  #输出yes

判断数字或者字符串是否相同:

[ $aa == $bb ]  #判断aa是否等于bb(字符串或者数字都可以)

[ $aa != $bb ]  #判断aa是否不等于bb(字符串或者数字都可以)

[ $aa == $bb ] && echo "yes" || echo "no"

2.条件语句,if

rate=`df -hT | grep "/boot" | awk '{print $6}' | cut -d "%" -f1`   #统计/boot目录下磁盘占用比例

echo "$rate"

if [ $rate -gt 80 ];then

    echo "waring, /boot disk is almost full"

elseif [ $rate -eq 100 ];then

    echo "/boot disk is full"

else

    echo "OK"

fi

猜你喜欢

转载自blog.csdn.net/u010397980/article/details/82812748