Linux Bash 脚本循环揭秘268


在 Linux Bash 脚本中,循环允许您重复执行一组命令,直到特定条件不再满足。这提供了自动化重复任务和遍历数据结构的强大方法,从而提高了脚本的效率和灵活性。

for 循环

for 循环针对序列中的一系列元素重复执行一组命令。其语法为:```bash
for variable in list
do
# 要执行的命令
done
```

其中:* `variable` 是用于保存序列中每个元素的变量。
* `list` 是要遍历的元素列表,可以用空格分隔或存储在数组中。
* `do` 和 `done` 标记循环的开始和结束。

例如,以下脚本使用 for 循环遍历数字 1 到 10,并打印每个数字:```bash
for i in {1..10}
do
echo $i
done
```

while 循环

while 循环只要条件为真就重复执行一组命令。其语法为:```bash
while condition
do
# 要执行的命令
done
```

其中:* `condition` 是要检查的条件。
* `do` 和 `done` 标记循环的开始和结束。

例如,以下脚本使用 while 循环不断提示用户输入,直到用户输入 "exit":```bash
while true
do
read input
if [ "$input" == "exit" ]
then
break
fi
done
```

until 循环

until 循环与 while 循环类似,但只要条件为假就重复执行一组命令。其语法为:```bash
until condition
do
# 要执行的命令
done
```

其中:* `condition` 是要检查的条件。
* `do` 和 `done` 标记循环的开始和结束。

例如,以下脚本使用 until 循环不断重试一个操作,直到成功:```bash
until command
do
sleep 1
done
```

遍历数组

Bash 脚本还可以使用 for 循环遍历数组中的元素。数组是一种存储一组有序元素的数据结构,可以用下标访问。

要遍历数组,可以使用以下语法:```bash
for element in "${array[@]}"
do
# 要执行的命令
done
```

其中:* `element` 是用于保存数组中每个元素的变量。
* `array[@]` 是要遍历的数组。

例如,以下脚本使用 for 循环遍历数字数组并打印每个数字:```bash
array=(1 2 3 4 5)
for i in "${array[@]}"
do
echo $i
done
```

Linux Bash 脚本中的循环提供了一种强大的方法来自动化重复任务并遍历数据结构。for、while、until 循环和数组遍历使脚本编写员能够创建高效且灵活的脚本。

2024-12-08


上一篇:bash 脚本实战案例:自动化任务和脚本化进程

下一篇:Bash脚本中的分号(:)