Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted
# 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

Output (e.g.):

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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