功能说明
脚本展示 xargs 的常见能力:把一行文件名变成 mkdir 参数、用 -I{} 为每个输入单独执行命令、用 -P4 并行运行 4 个任务、用 -0 安全处理 find -print0 的输出、用 -n2 每次传两个参数、用 export -f 让子进程调用 Bash 函数,以及用 -t 打印将要执行的命令。
关键代码
echo "file1 file2 file3" | xargs mkdir -p按空白拆分输入并追加到命令末尾,一次创建三个目录。printf "a\nb\nc\n" | xargs -I{} echo "Processing: {}"中{}是占位符,每个输入执行一次命令。xargs -P4 -I{} sh -c "..."最多同时运行 4 个任务,适合相互独立的批处理。find ... -print0 | xargs -0用空字符分隔,避免文件名中的空格和换行被误拆。xargs -n2 echo "Pair:"每次传入两个参数,输出形如Pair: 1 2。export -f process_file导出函数定义,随后bash -c启动的子 shell 才能调用它。xargs -t在执行前把完整命令打印到标准错误,可用于干跑检查。
使用注意
该示例会在当前工作目录创建 file1 到 file3 并在末尾用 rm -rf 删除,建议在专用临时目录中运行,避免误删同名文件。-I 与 -n 同时使用时 -n 会被忽略,脚本中 -n100 -I{} 的组合并不会真正分批。输入为空时部分 xargs 实现仍会执行一次命令,可加 -r 规避。并行任务若写同一文件,需要自行加锁。
验证方式
在临时目录执行脚本,观察三个目录被创建后又删除;并行部分 4 个任务应几乎同时开始并在约 1 秒内结束;-0 部分应正确列出 /etc 下的配置文件;-t 输出应显示实际命令。可用含空格的文件名测试 -0 与普通管道的差异。
代码示例
#!/usr/bin/env bash
set -euo pipefail
# Basic xargs: pass input as arguments
echo "file1 file2 file3" | xargs mkdir -p
# One argument per command
printf "a\nb\nc\n" | xargs -I{} echo "Processing: {}"
# Parallel execution (-P)
printf "1\n2\n3\n4\n" | xargs -P4 -I{} sh -c "echo Job {} starting; sleep 1; echo Job {} done"
# Null-delimited for safe filenames
find /etc -maxdepth 1 -name "*.conf" -type f -print0 2>/dev/null |
xargs -0 -I{} echo "Found: {}"
# Batch arguments
printf "1\n2\n3\n4\n5\n6\n" | xargs -n2 echo "Pair:"
# Parallel with progress
process_file() {
local file=$1
echo "Processing: $file"
sleep 0.5
echo "Done: $file"
}
export -f process_file
find /etc -maxdepth 1 -name "*.conf" -type f 2>/dev/null |
head -5 |
xargs -P4 -I{} bash -c "process_file "$@"" _ {}
# Dry run: show commands without executing
printf "file1\nfile2\nfile3\n" | xargs -t -I{} echo "Would process: {}"
# Handle large argument lists
find /usr -type f -name "*.so" 2>/dev/null |
xargs -n100 -I{} sh -c "echo Processing batch; ls -la {}" 2>/dev/null |
head -5
# Cleanup
rm -rf file1 file2 file3