if條件語句實例
1. if 在使用新的關鍵詞 (如 then else 等) 時雷客,可以另起一行,也可以用 ';' 分割烛卧;但 必須以 fi 結尾佛纫。
$ a="Hello"
$ b="World"
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'"; fi
'Hello' is not the same as 'World'
$ if [ "$a" != "$b" ]
then
echo "'$a' is not the same as '$b'"
fi
'Hello' is not the same as 'World'
上面兩種寫法都可以,得到的結果一致总放。
要以fi結尾呈宇,成對出現(xiàn)
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'";
>
# 如果不以 fi 結尾, shell 將顯示一個 > 符號局雄,等待用戶繼續(xù)輸入其它命令甥啄,如果這時,用戶自己手動再輸入 fi, 則結果將正常顯示:
'Hello' is not the same as 'World'
2. test, [ 和 [[ 在進行字符串比較時炬搭,可以使用 =, !=, -z, -n 等形式 (比如上例中的 !=)蜈漓, 也可以使用 > 或者 < (但 test 和 [ 使用 < 或 > 時需要轉義)穆桂,但三者在進行整數(shù)比較時,必須使用 -eq, -ne, -gt, -lt 等形式
$ c=11
$ d=2
$ if [ "$c" \> "$d" ]; then echo "$c is greater than $d"; else echo "$c is less than $d"; fi
11 is less than 2
$ if [ "$c" -gt "$d" ]; then echo "$c is greater than $d"; else echo "$c is less than $d"; fi
11 is greater than 2
# 對于整數(shù)比較融虽,我們需要使用 -gt 等表達式享完,如果使用 > 或 <, shell 將以字符串的形式比較而得到錯誤結果。
$ a="Ab"
$ b="a"
$ if [ "$a" > "$b" ]; then echo "This expression is wrong"; fi
This expression is wrong
$ if [ "$a" < "$b" ]; then echo "This expression is wrong"; fi
This expression is wrong
# 如果不進行轉義有额,> 和 < 僅被理解為重定向符般又,條件判斷結果始終為真。
$ if [ "$a" \< "$b" ]; then echo "'$a' is less than '$b'"; else echo "'$a' is greater than '$b'"; fi
'Ab' is less than 'a'
# 在字符串比較時巍佑,使用每個字母的ASCII數(shù)值來決定排序(小寫字母大于大寫字母)茴迁,并從第一位開始比較。
$ if [[ "$a" < "$b" ]]; then echo "'$a' is less than '$b'"; else echo "'$a' is greater than '$b'"; fi
'Ab' is greater than 'a'
# [[ 在比較字符串時不需要轉義萤衰,但是似乎對大小寫字母的大小判斷結果與 [ 不同堕义,我暫時還沒有查到原因,小伙伴們在使用時一定要注意脆栋。
3. test 和 [ 二者是一致的倦卖,即 'test expr' 與 [ expr ] 所起的作用完全相同。
$ a="Hello"
$ b="World"
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'"; fi
'Hello' not the same as 'World'
$ if test "$a" != "$b" ; then echo "'$a' is not the same as '$b'"; fi
'Hello' not the same as 'World'
4. [[ 是 test 和 [ 的加強版筹吐,支持 && 等形式邏輯判斷糖耸,進行算數(shù)擴展和正則表達比較等。
$ a=1
$ b=2
$ if [ $a -gt 0 -a $b > 0 ]; then echo "Both a and b are greater than 0"; fi
Both a and b are greater than 0
$ if [ $a -gt 0 && $b > 0 ]; then echo "Both a and b are greater than 0"; fi
-bash: [: missing `]'
$ if [[ $a -gt 0 && $b > 0 ]]; then echo "Both a and b are greater than 0"; fi
Both a and b are greater than 0
# [ 僅支持 -a (邏輯與) 和 -o (邏輯或) 這樣的邏輯操作符丘薛,而 [[ 支持 && 和 ||, 更靈活。
if [ "Hello World" =~ Hello ]; then echo "Example of regular expression comparison"; fi
-bash: [: =~: binary operator expected
if [[ "Hello World" =~ Hello ]]; then echo "Example of regular expression comparison"; fi
Example of regular expression comparison
# [[ 支持正則表達比較邦危,而 [ 不支持洋侨。
[ 和 [[ 才是 條件判斷命令,其后面跟著要判斷的條件 (空格分割倦蚪,很重要), ] 和 ]] 則表示條件判斷的結束
$ a=1
$ b=2
$ if [ $a==$b ]; then echo "$a equals $b"; fi
1 equals 2
$ if [[ $a==$b ]]; then echo "$a equals $b"; fi
1 equals 2
# 如果不加空格希坚,條件判斷不能正常進行
$ if [[ $a == $b ]]; then echo "$a equals $b"; else echo "Now you konw the importance of using space"; fi
Now you konw the importance of using space