In bash, the PIPESTATUS array holds the return values of commands in a pipeline.

Suppose that in the pipeline cmd1 | cmd2 | cmd3, the second command returns an error. Checking PIPESTATUS gives the index of the failed command, but how might one print the name of the command itself, cmd2?

It would be nice to show the arguments to cmd2 as well, but I will accept an answer that only prints the command name.

# 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]}"


# print returncode and failed command
for ((i=0;i<${#save[@]};i++)); do
  [[ ${save[$i]} -ne 0 ]] && echo "${save[$i]}: ${cmd[$i]}"

unset save cmd

Output (e.g.):

1: grep 1555
1: grep sh
| improve this answer | |
  • 1
    It's a shame there isn't a more elegant way, but this does do the job. – Nathaniel M. Beaver Mar 17 '15 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.