shell编程之四(条件判断语句)

简单的if结构

(如果满足if后面的表达式expression为真0,则执行command命令,然后退出,不满足就不执行command,直接退出)

    if expression
    then
        command
    fi
或则
    if expression;then
        command
    fi

例子(判断一个输入是否为空,并用exit返回指定值)

#!/bin/bash
echo "请输入一个字符串"
read a

if [ -z "$a" ];then
    echo "对不起,你未输入字符串"
    exit 1
fi

if/else简单结构

(如果满足if后面的表达式,则执行command1,如果不满足表达式,则执行else后面的command2命令)

    if expression;then
        command1
    else
        command2
    fi

if/else嵌套

(可以判断多个条件,注意不要漏掉fi)

    if expression1;then
        if expression2;then
            command1
        else
            command2
        fi
    else
        commadn3
    fi

if/elif/else结构

(用来解决上面那种容易漏掉fi的情况,提升可读性)

    if expression1;then
        command1
    elif expression2;then
        command2
    elif expression3;then
        command3
    else
        command4
    fi

case结构

(同样适用于多分支结构)

    case variable in
    value1)
        command1
        command2;;
    value2)
        command2;;
    value3)
        command3;;
    .......
    *)
        command;;
    esac

例子

    case "$mouth" in
    1)
        echo "this is 1 月";;
    2)
        echo "this is 2 月";;
    .........
    12)
        echo "this is 12 月";;
    *)
        echo "数字错误";;
    esac
声明:本文为原创,作者为 辣条①号,转载时请保留本声明及附带文章链接:https://boke.wsfnk.com/archives/510.html
谢谢你请我吃辣条谢谢你请我吃辣条

如果文章对你有帮助,欢迎点击上方按钮打赏作者

最后编辑于:2022/11/20作者: 辣条①号

现在在做什么? 接下来打算做什么? 你的目标什么? 期限还有多少? 进度如何? 不负遇见,不谈亏欠!

暂无评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

arrow grin ! ? cool roll eek evil razz mrgreen smile oops lol mad twisted wink idea cry shock neutral sad ???

文章目录