linux shell结构,linux——Shell的控制结构(附shell编写代码和运行结果)

针对shell的控制结构,也就是shell编程时所需要的三种控制流程,顺序/分支和循环。

在bash中,顺序可由简单的输入输出命令组成;分支语句由if、case实现;循环语句用for、while和until来实现。

一、if语句

1、基本的if语句

语句格式:

if condition

then

satements

else

statements

fi

92f7cd17ac9d160e92e40638cbe4135d.png

输出结果:

ec34ea97949a1f1c98a8108f228d9479.png

2、elif语句

elif语句格式:

if condition1

then

statements

elif condition2

then

statements

elif condition3

then

statements

……

else

statements

fi

dbe087efc093c4254c488ce2aecb64f3.png

输出结果:

82c9d21237cf1f6d5eca0f01f5a2c296.png

3、if语句其他形式

①if语句嵌套形式:

if condition ; then

if condition ; then

if condition ; then

statements

fi

fi

fi

②elif格式修改后:

if condition1 ; then

statements

elif condition2 ; then         statements

elif condition3 ; then         statements

……

else

statements

fi

7d7141919cc4a48891f90a9a1ff19d32.png

输出结果:

c0c2f284a3537670a933c6eb2577ce58.png

二、case语句

case是一个多分支结构,根据变量与各模式的匹配确定执行相应的语句序列。

case语句格式:

case variable in

pattern1) statements;;

pattern2) statements;;

pattern3) statements;;

……

patternn) statements;;

×) statements;;

esac

(1)简单的case脚本编写:

a2f8711a3ad52bfd82187cec8f5c532d.png

输出结果:

a0e9450cad654ad4512b6365006203e2.png

(2)case的合并匹配模式,即在每一个模式中,还可以使用通配符和逻辑符号

28a2af88fd5dd98da1b1077f720cc867.png

输出结果:

254b673b212d5f84cb29142c9df48716.png

(3)在case中,每个分支还可以执行多条命令:

bd73ecbf18a6f110211cd79376be27e0.png

输出结果:

c0f8aa1cdd65ef444138e5daf1b1cab2.png

三、for语句

for语句的语法格式:

for variable in values

do

statements

done

(1)简单的for脚本

65d6529714f5ef3e21aff6f6812c7b7b.png

输出结果:

10ded46a5d74c5e7c0b62478752e19bc.png

(2)在for循环中使用通配符

9594965b6ff0b0a7b613c7d814b295da.png

输出结果:

430537d514f98d709275896854459750.png

四、while语句

while语句格式:

while condition

do

statements

done

简单的while判断

28976c2e92bf017c47310894101808bd.png

输出结果:

dfd7bc7f02ff0b3c632dad0fe61e03a2.png

五、until语句

until语法格式:

until condition

do

statements

done

36064cc5ee27291eb47e6595fe4a734b.png

输出结果:

a90e3c96d6adac91ffb2320e9e8b1e81.png

六、break语句

break命令

break命令的功能是在控制条件为满足之前,跳出for、while或until循环。可以用break命令提供一个额外的数值参数来表明所要提跳出的循环层数,但一般情况下并不建议这么做,因为它将大大降低程序的可读性。

编写一个break脚本跳出if循环:

05bc9eddda5eb7206b07df4f1fe6ac7f.png

输出结果:

2657d1f78cce45d27f75b5573f33b01d.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值