Bash脚本中常用的循环结构有for循环和while循环,下面分别给出这两种循环的代码示例:
#!/bin/bash
# 使用for循环遍历数组
fruits=("apple" "banana" "orange" "grape")
for fruit in "${fruits[@]}"
do
echo "I like $fruit"
done
# 使用for循环遍历数字范围
for i in {1..5}
do
echo "Number: $i"
done
# 使用for循环遍历文件列表
for file in *
do
echo "File: $file"
done
#!/bin/bash
# 使用while循环读取文件内容
while read line
do
echo "Line: $line"
done < file.txt
# 使用while循环实现无限循环
count=1
while true
do
echo "Count: $count"
count=$((count+1))
sleep 1
done
这些示例演示了如何在Bash脚本中使用for循环和while循环。根据具体需求,可以灵活运用循环结构来完成不同的任务。
下一篇:Bash脚本的子命令出现问题。