單分支的if語句
if 判斷條件; then
條件為真的分支代碼
fi
單分支if結構的執行流程:首先判斷條件測試操作的結果,如果返回值為0表示條件成立,則執行then后面的命令序列,一直到遇見fi為止表示結束,繼續執行其他腳本代碼;如果返回不為0,則忽略then后面的命令序列,直接跳至fi行以后執行其他腳本代碼。
腳本代碼
[root@localhost bin]# cat ifsingle.sh #!/bin/bash if [ `id -u` -eq 0 ]; then echo "The current is to use the administrator account." fi
執行結果
[root@localhost bin]# ifsingle.sh The current is to use the administrator account.
雙分支的if語句
對于雙分支的選擇結構來說,要求針對“條件成立”、“條件不成立”兩種情況分別執行不同的操作。
if 判斷條件; then
條件為真的分支代碼
else
條件為假的分支代碼
fi
雙分支if結構的執行流程:首先判斷條件測試操作的結果,如果條件成立,則執行then后面的命令序列1,忽略else及后面的命令序列2,直至遇見fi結束判斷;如果條件不成立,則忽略then及后面的命令序列1,直接跳至else后面的命令序列2執行。直到遇見fi結束判斷。
腳本代碼
[root@localhost bin]# cat checkip.sh #!/bin/bash # Description: Test whether or not the remote host can communication read -p "Please input ip address: " ip ping -c1 -W1 $ip &> /dev/null if [ $? -eq 0 ]; then echo "Host is up" else echo "Host is down" fi
執行結果
[root@localhost bin]# checkip.sh Please input ip address: 10.1.252.252 Host is up [root@localhost bin]# checkip.sh Please input ip address: 10.1.252.22 Host is down
多分支
if 判斷條件1
then
判斷條件1為真的分支代碼
elif 判斷條件2
then
判斷條件2為真的分支代碼
elif 判斷條件n
then
判斷條件n為真的分支代碼
else
判斷條件n為假的分支代碼
fi
或
if 判斷條件1; then
判斷條件1為真的分支代碼
elif 判斷條件2; then
判斷條件2為真的分支代碼
elif 判斷條件n; then
判斷條件n為真的分支代碼
else
判斷條件n為假的分支代碼
fi
逐條件進行判斷,第一次遇為“真”條件時,執行其分支,而后結束整個if語句
多分支if結構的執行流程:首先判斷條件測試操作1的結果,如果條件1成立,則執行命令序列1,然后跳至fi結束判斷;如果條件1不成立,則繼續判斷條件測試操作2的結果,如果添加2成立,則執行命令序列2,然后跳至fi結束判斷;…..如果所有的條件都不滿足,則執行else后面地命令序列n,直到fi結束判斷。
實際上可以嵌套多個elif語句。If語句的嵌套在編寫Shell腳本是并不常用,因此多重嵌套容易使程序結構變得復雜。當確實需要使用多分支的程序結構是,建議采用case語句要更加方便。
腳本代碼
[root@localhost bin]# cat checkgrade.sh #!/bin/bash # Description: read -p "input you grade(0-100):" grade if [ $grade -ge 85 ] && [ $grade -le 100 ]; then echo "you grade is very good!" elif [ $grade -ge 60 ] && [ $grade -le 84 ]; then echo "you grade is good!" elif [ $grade -gt 100 ]; then echo "error! please input 0-100!" else echo "you so bad!" fi
執行結果
[root@localhost bin]# checkgrade.sh input you grade(0-100):80 you grade is good! [root@localhost bin]# checkgrade.sh input you grade(0-100):50 you so bad! [root@localhost bin]# checkgrade.sh input you grade(0-100):98 you grade is very good! [root@localhost bin]# checkgrade.sh input you grade(0-100):33 you so bad!
原創文章,作者:cyh5217,如若轉載,請注明出處:http://www.www58058.com/36012