欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/3/8 25 豆豆
生活随笔 收集整理的这篇文章主要介绍了 linux shell结构,linux——Shell的控制结构(附shell编写代码和运行结果) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

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

一、if语句

1、基本的if语句

语句格式:

if condition

then

satements

else

statements

fi

输出结果:

2、elif语句

elif语句格式:

if condition1

then

statements

elif condition2

then

statements

elif condition3

then

statements

……

else

statements

fi

输出结果:

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

输出结果:

二、case语句

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

case语句格式:

case variable in

pattern1) statements;;

pattern2) statements;;

pattern3) statements;;

……

patternn) statements;;

×) statements;;

esac

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

输出结果:

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

输出结果:

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

输出结果:

三、for语句

for语句的语法格式:

for variable in values

do

statements

done

(1)简单的for脚本

输出结果:

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

输出结果:

四、while语句

while语句格式:

while condition

do

statements

done

简单的while判断

输出结果:

五、until语句

until语法格式:

until condition

do

statements

done

输出结果:

六、break语句

break命令

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

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

输出结果:

总结

以上是生活随笔为你收集整理的linux shell结构,linux——Shell的控制结构(附shell编写代码和运行结果)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。