linux 中if条件判断语句
1、linux中if条件判断语句,基本结构:
if 条件判断语句
then
command
fi
[root@centos7pc1 test2]# ls test.sh [root@centos7pc1 test2]# cat test.sh ## 脚本文件 #!/bin/bash if [ ! -e xxxx ] ## if + 条件判断语句 then ## then为基本结构 mkdir xxx &> /dev/null ## &> 表示标准输出和标准错误输出 fi ## fi为基本结构 [root@centos7pc1 test2]# bash test.sh [root@centos7pc1 test2]# ls test.sh xxx [root@centos7pc1 test2]# bash test.sh [root@centos7pc1 test2]# ls test.sh xxx
2、if …. else
[root@centos7pc1 test2]# ls test.sh [root@centos7pc1 test2]# cat test.sh #!/bin/bash ping -c 3 $1 &> /dev/null if [ $? -eq 0 ] ## 利用$? 判断上一步的执行结果,上一步成功执行则返回0, 否则返回其他数 then echo "$1 is online!" else echo "$1 is not online!" fi [root@centos7pc1 test2]# bash test.sh www.baidu.com www.baidu.com is online!
3、if … elif … else
[root@centos7pc1 test2]# ls test.sh [root@centos7pc1 test2]# cat test.sh #!/bin/bash read -p "please input your score: " SCORE ## 输入分数 if [ $SCORE -ge 80 ] && [ $SCORE -le 100 ] then echo "execllent!" elif [ $SCORE -ge 60 ] && [ $SCORE -lt 80 ] then echo "pass!" elif [ $SCORE -ge 0 ] && [ $SCORE -lt 60 ] then echo "failture!" else echo "out of the score range!!!" fi [root@centos7pc1 test2]# bash test.sh please input your score: 89 execllent! [root@centos7pc1 test2]# bash test.sh please input your score: 78 pass! [root@centos7pc1 test2]# bash test.sh please input your score: 33 failture! [root@centos7pc1 test2]# bash test.sh please input your score: 234 out of the score range!!!