详解shell for循环

树叶云

除了 while 循环和 until 循环,Shell 脚本还提供了 for 循环,它更加灵活易用,更加简洁明了,下面为大家简单介绍一下shell for循环的使用方法。

for循环一般格式为:

for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done

写成一行:

for var in item1 item2 ... itemN; do command1; command2… done;

当变量值在列表里,for循环即执行一次所有命令,使用变量名获取列表中的当前取值。命令可为任何有效的shell命令和语句。in列表可以包含替换、字符串和文件名。

in列表是可选的,如果不用它,for循环使用命令行的位置参数。

例如,顺序输出当前列表中的数字:

for loop in 1 2 3 4 5
doecho "The value is: $loop"done

输出结果:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

顺序输出字符串中的字符:

for str in 'This is a string'doecho $strdone

输出结果:

This is a string

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/221937.html<

(0)
运维的头像运维
上一篇2025-04-15 06:35
下一篇 2025-04-15 06:36

相关推荐

发表回复

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