Shell程式設計-06-Shell中的if語句
阿新 • • 發佈:2018-12-21
在任何一門語言中,判斷語句總是少不了,今天來學習一下Shell中的if語句。
基本語法
單分支情況
- 第一種語法
if <條件表示式>
then
語句
fi
- 第二種語法
if <條件表示式>;then
語句
fi
其中條件表示式部分可以是test、[]、[[]]和(())等條件表示式。以上兩種格式,可根據自己實際情況選擇一種即可。
雙分支情況
if <條件表示式>
then
語句
else
語句
fi
多分支情況
if <條件表示式> then 語句 elif <條件表示式> then 語句 elif <條件表示式> then 語句 else 語句 fi
在多分支的if中,每個elif中後均需要帶有then
分支巢狀情況
if <條件表示式>
then
if <條件表示式>
then
語句
fi
fi
在以上的寫法注意縮排,方便閱讀
建議在一個if巢狀不要超過三層
if與條件表示式語法
在前面講過各個條件測試表達式,如test、[]、[[]]和(())等條件表示式,如下所示:
- 1、test表示式
if test <表示式>
then
語句
fi
- 2、[]表示式
if [ <表示式> ] then 語句 fi
- 3、[ [ ] ]表示式
if [[ <表示式> ]]
then
語句
fi
- 4、(( ))表示式
if (( <表示式> ))
then
語句
fi
- 5、命令表示式
if 命令
then
語句
fi
if示例
1、if示例:判斷檔案是否且為普通檔案
[[email protected] ~]# [ -f /etc/passwd ] && echo true || echo false true [[email protected] ~]# test -f /etc/passwd && echo true || echo false true
與以下寫法等效
[[email protected] Test]# cat if.sh
#!/bin/bash
if [ -f "$1" ]
then
echo true
else
echo false
fi
if test -f "$2"
then
echo true
else
echo false
fi
[[email protected] Test]# bash if.sh /etc/passwd /etc/hostssss
true
false
2、if示例:比較輸入數字的大小
[[email protected] Test]# cat compareNum.sh
#!/bin/bash
a=$1
b=$2
echo "Inputed number is:" ${a} ${b}
if [ $# -ne 2 ]
then
echo "input number must be 2 number."
exit 2
fi
expr $a + 2 &> /dev/null # 檢查是否為整數
resulta=$?
expr $b + 2 &> /dev/null # 檢查是否為整數
resultb=$?
if [ $resulta -eq 0 -a $resultb -eq 0 ] # 判斷檢查結果
then
if [ $a -gt $b ]
then
echo "$a > $b"
elif [ $a -lt $b ]
then
echo "$a < $b"
elif [ $a -eq $b ]
then
echo "$a = $b"
else
echo "error"
fi
else
echo "please check your input"
fi
[[email protected] Test]# bash compareNum.sh 1 # 輸入一個數字
Inputed number is: 1
input number must be 2 number.
[[email protected] Test]# bash compareNum.sh a b # 輸入字母
Inputed number is: a b
please check your input
[[email protected] Test]# bash compareNum.sh 900 89 # 輸入兩個數字
Inputed number is: 900 89
900 > 89
[[email protected] Test]# bash compareNum.sh 89 900
Inputed number is: 89 900
89 < 900
[[email protected] Test]# bash compareNum.sh 900 900
Inputed number is: 900 900
900 = 900
本文同步在微信訂閱號上釋出,如各位小夥伴們喜歡我的文章,也可以關注我的微信訂閱號:woaitest,或掃描下面的二維碼新增關注: