本文目录导读:

命令行工具批量执行指令有多种方法,以下是几种常见且实用的方式:
Shell 循环与条件
for 循环
# 对多个文件执行相同命令
for file in *.txt; do
echo "处理文件: $file"
wc -l "$file"
done
# 明确列表
for ip in 192.168.1.1 192.168.1.2 192.168.1.3; do
ping -c 1 "$ip"
done
# 数字范围
for i in {1..10}; do
touch "file_$i.txt"
done
while 循环
# 从文件读取
while read host; do
ssh "$host" "uptime"
done < hosts.txt
# 无限循环(直到条件满足)
count=0
while [ $count -lt 5 ]; do
echo "执行次数: $count"
((count++))
done
使用 xargs 命令
# 从管道接收参数并执行
find . -name "*.log" -type f | xargs rm
# 并行执行(-P 参数)
seq 1 10 | xargs -I {} -P 4 sh -c 'sleep 1; echo "任务 {} 完成"'
# 安全处理文件名(含空格)
find . -name "*.mp3" -print0 | xargs -0 -I {} cp "{}" /backup/
使用 parallel 工具
GNU Parallel 是非常强大的并行执行工具(需安装 sudo apt install parallel):
# 基本用法
parallel echo "并行执行任务 {}" ::: 1 2 3 4 5
# 处理文件
ls *.jpg | parallel convert {} {.}.png
# 组合参数
parallel -j4 ssh {} "uptime" ::: server1 server2 server3 server4
# 远程执行命令
parallel -S server1,server2,server3 "hostname && uptime"
使用后台进程 & 和 wait
# 并行执行多个后台任务
for i in {1..5}; do
(
sleep $((RANDOM % 5))
echo "任务 $i 完成"
) &
done
wait # 等待所有后台任务完成
echo "所有任务完成"
使用脚本文件
将命令写入文件批量执行:
# 创建脚本文件 commands.sh #!/bin/bash command1 command2 command3 # 执行脚本 chmod +x commands.sh ./commands.sh # 或 bash commands.sh
在远程服务器批量执行
SSH 循环
for server in s1.example.com s2.example.com s3.example.com; do
ssh "$server" "bash -s" < local_script.sh
done
使用 sshpass 自动化密码
for ip in $(cat servers.txt); do
sshpass -p 'password' ssh user@"$ip" "command"
done
特殊场景示例
批量重命名文件
for file in *.JPG; do
mv "$file" "${file%.JPG}.jpg"
done
批量执行 SQL
for db in database1 database2 database3; do
mysql -u root -p"password" "$db" < script.sql
done
并行下载
urls=("http://example.com/file1" "http://example.com/file2")
for url in "${urls[@]}"; do
(wget "$url" &> /dev/null && echo "下载完成: $url") &
done
wait
实用技巧
使用 subshell 避免环境污染
# 将批量操作放在子 shell 中
(
cd /tmp
for file in *.tmp; do
rm "$file"
done
)
# 当前目录不受影响
错误处理
# 带错误处理的循环
for cmd in task1 task2 task3; do
if $cmd; then
echo "✓ $cmd 成功"
else
echo "✗ $cmd 失败" >&2
fi
done
进度显示
total=$(wc -l < files.txt)
current=0
while read file; do
((current++))
echo -ne "进度: $current/$total\r"
process "$file"
done < files.txt
echo -e "\n完成!"
选择建议
- 简单重复任务:使用
for循环 - 从文件读取输入:使用
while read - 需要并行处理:使用
xargs -P或parallel - 复杂命令序列:使用脚本文件
- 远程批量操作:使用 SSH 循环或并行 SSH 工具
这些方法可以组合使用,根据具体需求选择最合适的方案。
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。