天天看點

條件選擇if語句

單分支的if語句

if 判斷條件:then

條件為真的分支代碼

fi

單分支if結構的執行流程:首先判斷條件測試操作的結果,如果傳回值為0表示條件成立,則執行then後面的指令序列,一直到遇見fi為止表示結束,繼續執行其他腳本代碼;如果傳回不為0,則忽略then後面的指令序列,直接跳至fi行以後執行其他腳本代碼。

條件選擇if語句

腳本代碼

[root@localhostbin]# cat ifsingle.sh

#!/bin/bash

if[ `id -u` -eq 0 ]; then

       echo "The current is to use theadministrator account."

執行結果

[root@localhostbin]# ifsingle.sh

Thecurrent is to use the administrator account.

雙分支的if語句

對于雙分支的選擇結構來說,要求針對“條件成立”、“條件不成立”兩種情況分别執行不同的操作。

if 判斷條件; then

else

條件為假的分支代碼

雙分支if結構的執行流程:首先判斷條件測試操作的結果,如果條件成立,則執行then後面的指令序列1,忽略else及後面的指令序列2,直至遇見fi結束判斷;如果條件不成立,則忽略then及後面的指令序列1,直接跳至else後面的指令序列2執行。直到遇見fi結束判斷。

條件選擇if語句

[root@localhostbin]# cat checkip.sh

#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"

       echo "Host is down"

[root@localhostbin]# checkip.sh

Please input ipaddress: 10.1.252.252 

Host is up

Please input ipaddress: 10.1.252.22

Host is down

多分支的if語句

if 判斷條件1

then

判斷條件1為真的分支代碼

elif 判斷條件2

     判斷條件2為真的分支代碼

elif 判斷條件n

判斷條件n為真的分支代碼

     判斷條件n為假的分支代碼

if 判斷條件1; then

elif 判斷條件2; then

elif 判斷條件n; then

逐條件進行判斷,第一次遇為“真”條件時,執行其分支,而後結束整個if語句

多分支if結構的執行流程:首先判斷條件測試操作1的結果,如果條件1成立,則執行指令序列1,然後跳至fi結束判斷;如果條件1不成立,則繼續判斷條件測試操作2的結果,如果添加2成立,則執行指令序列2,然後跳至fi結束判斷;…..如果所有的條件都不滿足,則執行else後面地指令序列n,直到fi結束判斷。

實際上可以嵌套多個elif語句。If語句的嵌套在編寫Shell腳本是并不常用,是以多重嵌套容易使程式結構變得複雜。當确實需要使用多分支的程式結構是,建議采用case語句要更加友善。

條件選擇if語句

[root@localhost bin]# cat checkgrade.sh

# Description:

read -p "input you grade(0-100):" grade

if [ $grade -ge 85 ] && [ $grade -le 100 ]; then

       echo "you grade is verygood!"

elif [ $grade -ge 60 ] && [ $grade -le 84 ]; then

       echo "you grade isgood!"

elif [ $grade -gt 100 ]; then

       echo "error! pleaseinput 0-100!"

       echo "you so bad!"

[root@localhost bin]# checkgrade.sh

input you grade(0-100):80

you grade is good!

input you grade(0-100):50

you so bad!

input you grade(0-100):98  

you grade is very good!

[root@localhost bin]# checkgrade.sh

上一篇: py條件語句