shell中的if語句
1. if語句的基本格式
if condition #如果滿足condition條件
then
statement(s) #就執行statement(可以有多個)
fi
注意:這裏的then和if可以位於一行,位於一行時condition後要加分號:
if condition;then
statement
fi
例1:
#!/bin/bash
if date #如果能夠正常執行date命令
then
echo "it works" #就輸出it works
fi #date命令的執行結果也會被輸出
例2:
#!/bin/bash
if datfff #如果能夠正常執行datefff命令
then
echo "it works" #就輸出it works
fi #如果不能執行datefff,就跳出if語句,執行下面的內容
echo "we are outside if the if statement"
例3:
#!/bin/bash
testing=student
if grep $testing /etc/passwd
then
echo The bash files for user $testing are:
ls -a /home/$testing/.b*
fi
例4:
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a和b相等"
fi
例5:
#!/bin/bash
read num1
read num2
if (( $num1 >18 && $num2 < 60 ))
then
echo $num1
echo $num2
fi
2. if-else語句
如果語句有兩個分支,就可以使用if-else語句
格式:
if condition
then
statement1
else
statement2
fi
如果condition成立,那麼then後面的statement1將會被執行;
否則,執行else後面的statement2語句
例:
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a和b相等"
else
echo "a和b不相等"
fi
3. if-elif-else語句
shell支持任意數目的分支,當分支比較多時,可以使用if elif else 結構
格式:
if condition1
then
statement1
elif condition2
then
statement2
elif condition3
then
statement3
......
else
statementn
fi
注意:if和eilf後面後要跟then
整條語句的執行邏輯爲:
如果condition1成立,那麼就執行if後面的statement1;如果condition1不成立,就繼續執行elif,判斷condition2;
如果condition2成立,那麼就執行if後面的statement2;如果condition2不成立,就繼續執行elif,判斷condition3;
以此類推…
如果所有的if和elif判斷都不成立,就進入最後的else,執行statementn。
例:
#!/bin/bash
read age
if (($age<=2));then
echo "嬰兒"
elif (($age>=3 && $age<=8));then
echo "幼兒"
elif (($age>=9 && $age<=17));then
echo "少年"
elif (($age>=18 && $age<=25));then
echo "成年"
elif (($age>=26 && $age<=40));then
echo "青年"
elif (($age>=41 && $age<=60));then
echo "中年"
else
echo "老年"
fi