在 中bash
,PIPESTATUS
数组保存管道中命令的返回值。
假设在 pipeline 中cmd1 | cmd2 | cmd3
,第二个命令返回错误。检查PIPESTATUS
给出了失败命令的索引,但是如何打印命令本身的名称呢cmd2
?
最好cmd2
也显示参数,但我会接受仅打印命令名称的答案。
答案1
# put commands in an array, e.g.: cat /etc/passwd | grep 1555 | grep sh
cmd=("cat /etc/passwd" "grep 1555" "grep sh")
# execute commands
eval "${cmd[0]}" | eval "${cmd[1]}" | eval "${cmd[2]}"
# save PIPESTATUS
save=("${PIPESTATUS[@]}")
# print returncode and failed command
for ((i=0;i<${#save[@]};i++)); do
[[ ${save[$i]} -ne 0 ]] && echo "${save[$i]}: ${cmd[$i]}"
done
unset save cmd
输出(例如):
1:grep 1555 1:grep sh