与其他编程语言类似,Shell支持for循环。
for循环一般格式为:
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。
例如,顺序输出当前列表中的数字:
运行结果:
顺序输出字符串中的字符:
运行结果:
显示主目录下以 .bash 开头的文件:
运行结果:
for循环一般格式为:
for 变量 in 列表
do
command1
command2
...
commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。
例如,顺序输出当前列表中的数字:
- for loop in 1 2 3 4 5
- do
- echo "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'
- do
- echo $str
- done
This is a string
显示主目录下以 .bash 开头的文件:
- #!/bin/bash
- for FILE in $HOME/.bash*
- do
- echo $FILE
- done
/root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc
本文介绍了如何在Shell脚本中使用for循环。详细解释了for循环的基本语法,并通过几个实例展示了如何利用for循环来处理一系列任务,包括遍历数字列表、字符串以及文件系统中的文件。
11万+

被折叠的 条评论
为什么被折叠?



