IF语句

选择执行:

注意: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


逐条进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句


例子1:年龄判别

需求:

第1段:0到18(18岁以下,不包含18岁)好好学习,天天向上

第2段:18到60(18岁到60岁,包含60岁)努力工作

第3段:60-150(60岁到150岁,包含150岁)享受生活

其他情况:你不是来自地球


代码如下:

#!/bin/bash

read -p "Please input your age: " AGE

if [ "$AGE" -lt 18 ];then

	echo "good good study;day day up"

elif [ "$AGE" -le 60 ];then

	echo "work hard"

elif [ "$AGE" -le 150 ];then

	echo "enjoy your life"

else

	echo "you do not come from the earth!"

fi


例子2:回答yes or no

代码如下:

read -p "Please input your answer: " ANSWER

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

yes or no.png-2.png
yes or no.png


例子3:嵌套

效果图,判断是否富有与帅

1.png

代码如下:

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 

富有与帅.png


  1. [:digit:] ↩︎

posted on 2018-08-30 11:56  圆缘  阅读(234)  评论(0编辑  收藏  举报

返顶部