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!!!