Bash

在 bash 中列印第 n 個管道命令

  • March 14, 2015

bash中,PIPESTATUS數組保存管道中命令的返回值。

假設在 pipelinecmd1 | cmd2 | cmd3中,第二個命令返回錯誤。檢查PIPESTATUS給出了失敗命令的索引,但是如何列印命令本身的名稱cmd2

最好也顯示參數cmd2,但我會接受一個只列印命令名稱的答案​​。

# 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

引用自:https://unix.stackexchange.com/questions/190094