程序執行三種順序
順序執行
選擇執行
循環執行
選擇執行語句:
if語句
格式:
單分支:
if 判斷條件;then
條件分支代碼
fi
雙分支:
if 判斷條件;then
條件為真時語句
else (此處不會對給出的條件做判斷)
條件為假時語句
fi
多分支:
if 條件1;then
代碼
elif 條件2;then
代碼
elid 條件2;then
代碼
else
代碼
fi
例子:輸入兩個數,判斷其大小
[root@centos7 bin]# cat f1 #!/bin/bash read -p "input a number:" m read -p "input a number:" n if [ $m -gt $n ];then echo "$m >$n" else [ $m = $n ] 此程序中,else后面的判斷無效,如果m=n或者m<n都會走else分支,若想只要條件符合的輸出需要將else換成elif echo " $m = $n" fi [root@centos7 bin]# [root@centos7 bin]#
if語句例子
if ping – c1 – W2 station1 &> /dev/null; then
echo 'Station1 is UP'
elif grep "station1" ~/maintenance.txt &> /dev/null
then
echo 'Station1 is undergoing maintenance‘
else
echo 'Station1 is unexpectedly DOWN!'
exit 1
fi
條件判斷case
case 變量 in
pat1)
分支1
;;
part2)
分支2
;;
part3)
分支3
;;
esac
注意:case 支持glob的通配符
循環語句綜合練習: 1、寫一個腳本/root/bin/createuser.sh,實現如下功能:使用一個用戶名做為參數,如果指定參數的用戶存在,就顯 示其存在,否則添加之;顯示添加的用戶的id號等信息 2、寫一個腳本/root/bin/yesorno.sh,提示用戶輸入yes或no,并判斷用戶輸入的是yes還是no,或是其它信息 3、寫一個腳本/root/bin/filetype.sh,判斷用戶輸入文件路徑,顯示其文件類型(普通,目錄,鏈接,其它文件類型) 4、寫一個腳本/root/bin/checkint.sh,判斷用戶輸入的參數是否為正整數
答案:1 [root@centos7 bin]# cat useradd.sh #!/bin/bash read -p "please input the username:" username if id -u $username &>/dev/null ;then echo "the user $username exit" else useradd $username echo "useradd success,userID is `id -u $username`" fi [root@centos7 bin]# 答案:2 [root@centos7 bin]# cat caseyesorno.sh #!/bin/bash read -p "please input yes or no:" yn case $yn in yes|y|0|Y|[yY][Ee][Ss]) echo "you input is: $yn" ;; no|[Nn][Oo]|N|n) echo "you input is:$yn" ;; *) echo "you input is other" esac [root@centos7 bin]# [root@centos7 bin]# cat yesorno.sh #!/bin/bash read -p "please input yes or no:" yn if [[ $yn =~ [yY][eE][sS] ||[Yy] ]] ;then echo "you input is: yes" elif [[ $yn =~ [nN][oO] || [Nn] ]];then echo "you input is:no" else echo "you input is other" fi [root@centos7 bin]# 答案:3 [root@centos7 bin]# cat filetype.sh #!/bin/bash read -p "please input filename:" filename [ ! -e $filename ] && echo "filename not exit"&&exit if [ -h $filename ] ;then 注意:軟鏈接文件也被識別為普通文件,正確判斷出軟鏈接文件,將-h條件放到-f文件前去判斷 echo "filetype is symolink file" elif [ -d $filename ] ;then echo "filetype is dirction" elif [ -f $filename ] ;then echo "filetype is common file" else echo "filetype is other" fi [root@centos7 bin]# 答案:4 [root@centos7 bin]# cat checkint.sh #!/bin/bash read -p "please input a num:" num if [ $num -lt 1 ] ;then echo "please input a init" elif [[ $num =~ ^[[:digit:]]+$ ]];then echo "you input is a int" else echo "input error" fi [root@centos7 bin]#
原創文章,作者:wangnannan,如若轉載,請注明出處:http://www.www58058.com/35866