bash shell基本语法之控制语句

前言

shell中也可以使用类似其它语言的if-else、switch-case等分支语句,虽然和其它语言在语法上存在一定区别,但是语义上差不多。下面对其控制语句的写法做一个示例说明。

关于分支使用的逻辑表达的语法在bash shell基本语法之逻辑表达式有说明。

控制语句写法示例

if语句

只有一个分支:if-then

语法:

if 逻辑表达结果为true;then

    执行相关操作

fi

p.s.:then关键字如果不重新写一行,记得前面加那个分号(;)

示例:

#! /bin/bash

if [ 2 -gt 1 ];then
        echo "2 > 1"
fi

两个分支:if-then-else

写法:

if 表达式为真;then

    执行表达1

else

    执行表达式2

fi

示例:

if [ 2 -lt 1 ];then
        echo "2 < 1"
else
        echo "2 > 1"
fi

多个分支:if-then-elif-...-else

写法:

if 表达式1为真;then

    执行操作1

elif 表达式2为真;then

    执行操作2

elif 表达式3为真;then

    执行操作3

.......可以有多个elif

else

     前面条件都不满足,执行这个操作

fi

最后的else也可以不要,这样的话,如果条件都不满足,就都不执行。

示例:

#! /bin/bash

number=$1
if [ "x$number" = "x" ];then
        echo "number is null"
elif [ $number -eq 1 ];then
        echo "number is 1"
elif [ $number -eq 2 ];then
        echo "number is 2"
elif [ $number -eq 3 ];then
        echo "number is 3"
else
        echo "number is unknown"
fi

示例中$1是位置参数,需要了解可以看bash shell基本语法之特殊变量的使用

case语句

多个会支条件的时候,可以使用case语法,语义上很类似C或java的switch case,但是感觉更强大点,同样,它的匹配条件也不算是表达式,而是匹配否个值是否相等(存在)

写法:

case 变量 in

    匹配条件1)

        执行操作1;;

    匹配条件2)

        执行操作2;;

    *)

        都不匹配,执行的操作;;

esac

注意上面的写法,每个匹配条件后面跟一个),另外,每个执行的代码后面有两个分号,类似于c/java的break。当然,在bash的的帮助文档上,这两个分号";;",可以换成";&"或者";;&“,有其它作用,下面文档上的说明:

 If the ;; operator is used, no subsequent matches are attempted after the
              first  pattern  match.  Using ;& in place of ;; causes execution to continue with the list associated with the
              next set of patterns.  Using ;;& in place of ;; causes the shell to test the next pattern list in  the  state‐
              ment,  if  any,  and execute any associated list on a successful match. 

有兴趣的可以试一下,最后的*),就是前面的条件都不匹配的时候执行的(default)。

现在写一个这个匹配条件的几种写法(并不全),随便看下,心里有个数:

#! /bin/bash

case $1 in
        1)
                echo "input is 1";;
        2)
                echo "input is 2";;
        'a')
                echo "input is a";;
        'b'|'c')
                echo "input is b|c";;
        [A-Z])
                echo "input is [A-Z]";;
        *)
                echo "unknown input";;

esac

执行结果:

p.s. :匹配条件可以是一个字符串或者多个字符串,不一定只是一个字符,示例中都是一个字符。

其实case+shift很适合解析参数选项,后面的博文如果写shift的时候,会写一个示例。

发布了136 篇原创文章 · 获赞 81 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/x763795151/article/details/96764387
今日推荐