选择执行:
注意:if语句可嵌套
1.单分支
if 判断条件;then
条件为真的分支代码
fi
2.双分支
if 判断条件; then
条件为真的分支代码
else
条件为假的分支代码
fi
3.多分支
if 判断条件1; then
条件1为真的分支代码
elif 判断条件2; then
条件2为真的分支代码
elif 判断条件3; then
条件3为真的分支代码
else
以上条件都为假的分支代码
fi
例子1:年龄判别
需求:
第1段:0到18(18岁以下,不包含18岁)好好学习,天天向上
第2段:18到60(18岁到60岁,包含60岁)努力工作
第3段:60-150(60岁到150岁,包含150岁)享受生活
其他情况:你不是来自地球
代码如下:
#!/bin/bash
echo "good good study;day day up"
echo "work hard"
echo "enjoy your life"
else
echo "you do not come from the earth!"
fi
例子2:回答yes or no
代码如下:
if [[ $ANSWER =~ [Y|y]([E|e][S|s])? ]];then
echo "your answer is yes"
elif [[ $ANSWER =~ [N|n][O|o]? ]];then
echo "your answer is no"
else
echo "your answer is wrong"
fi
echo "good good study;day day up"
echo "work hard"
echo "enjoy your life"
else
echo "you do not come from the earth!"
fi
例子2:回答yes or no
代码如下:
if [[ $ANSWER =~ [Y|y]([E|e][S|s])? ]];then
echo "your answer is yes"
elif [[ $ANSWER =~ [N|n][O|o]? ]];then
echo "your answer is no"
else
echo "your answer is wrong"
fi
echo "good good study;day day up"
echo "work hard"
echo "enjoy your life"
else
echo "you do not come from the earth!"
fi
例子2:回答yes or no
代码如下:
if [[ $ANSWER =~ [Y|y]([E|e][S|s])? ]];then
echo "your answer is yes"
elif [[ $ANSWER =~ [N|n][O|o]? ]];then
echo "your answer is no"
else
echo "your answer is wrong"
fi
echo "enjoy your life"
echo "you do not come from the earth!"
if [[ $ANSWER =~ [Y|y]([E|e][S|s])? ]];then
echo "your answer is yes"
elif [[ $ANSWER =~ [N|n][O|o]? ]];then
echo "your answer is no"
else
echo "your answer is wrong"
fi
例子3:嵌套
效果图,判断是否富有与帅
代码如下:
read -p "Are you rich: " ANSWER
if [[ "$ANSWER" =~ ^[Y|y]([E|e][S|s])?$ ]];then
echo "OK!"
elif [[ "$ANSWER" =~ ^[N|n][O|o]?$ ]];then
read -p "Are you handsome: " ANSWER
if [[ "$ANSWER" =~ ^[Y|y]([E|e][S|s])?$ ]];then
echo "OK!"
elif [[ "$ANSWER" =~ ^[N|n][O|o]?$ ]];then
echo "work hard!"
else
echo "Your answer is wrong!"
fi
else
echo "Your answer is wrong!"
fii
-
[:digit:] ↩︎