开发工具

Shell for 循环结构

13 篇文章69 次收藏
上一节:Shell case 语句下一节:Shell while 语句

在 Shell 脚本中,for 循环是一种常用的迭代结构,用于遍历列表或范围内的元素。以下是 Shell for 循环的完整语法和典型用法:

一、基本语法

for 变量 in 列表
do
    # 循环体命令
done



二、常见用法示例

1. 遍历字符串列表

for fruit in apple banana cherry
do
    echo "当前水果: $fruit"
done

# 输出:
# 当前水果: apple
# 当前水果: banana
# 当前水果: cherry


2. 遍历文件

for file in *.txt   # 遍历当前目录所有.txt文件
do
    echo "处理文件: $file"
    # 例如:mv "$file" "${file%.txt}.bak"
done


3. 遍历数字范围

# 方法1:大括号扩展(Bash特有)
for i in {1..5}     # 生成1到5的序列
do
    echo "数字: $i"
done

# 方法2:使用seq命令(兼容性强)
for i in $(seq 1 2 10)  # 生成1到10,步长2 → 1 3 5 7 9
do
    echo "奇数: $i"
done


4. 遍历数组

colors=("red" "green" "blue")
for color in "${colors[@]}"
do
    echo "颜色: $color"
done


5. C语言风格循环(Bash支持)

for ((i=0; i<5; i++))
do
    echo "索引: $i"
done



三、高级用法

1. 遍历命令行参数

for arg in "$@"     # "$@" 表示所有参数
do
    echo "参数: $arg"
done

# 带索引遍历
index=1
for arg in "$@"
do
    echo "参数$index: $arg"
    ((index++))
done


2. 遍历目录和子目录文件

# 使用find命令递归查找
for file in $(find /path -type f -name "*.log")
do
    echo "日志文件: $file"
done



四、循环控制

1. break 中断循环

for num in {1..10}
do
    if [ $num -eq 5 ]; then
        break
    fi
    echo "数字: $num"
done
# 输出:1 2 3 4


2. continue 跳过当前迭代

for num in {1..5}
do
    if [ $num -eq 3 ]; then
        continue
    fi
    echo "数字: $num"
done
# 输出:1 2 4 5



五、实际应用场景

1. 批量重命名文件

# 为所有.jpg文件添加日期前缀
for file in *.jpg
do
    mv "$file" "$(date +%Y%m%d)_$file"
done


2. 多服务器命令执行

servers=("web1" "web2" "db1")
for server in "${servers[@]}"
do
    ssh "$server" "systemctl restart nginx"
done


3. 日志文件压缩

# 压缩7天前的日志
for logfile in /var/log/*.log
do
    if [ $(find "$logfile" -mtime +7) ]; then
        gzip "$logfile"
    fi
done



六、注意事项

1、变量名规范

避免使用 $i 或 $file 之外的保留字(如 $PATH)。


2、空格处理

如果列表项含空格,用双引号包裹变量:

for file in "file name.txt" "another file.doc"


3、性能优化

遍历大量文件时,使用 find -exec 或 xargs 更高效:

find . -name "*.tmp" -exec rm {} \;


通过灵活运用 for 循环,可以轻松处理文件批量操作、数据遍历和自动化任务。建议结合具体需求选择最合适的遍历方式。



上一节:Shell case 语句下一节:Shell while 语句