1

I have a custom $PROMPT_COMMAND in bash that logs the last executed command and its return code. I was using $? for the latter happily until I realized that for piped commands this was insufficient. I thought I'd log ${PIPESTATUS[@]} instead.

Unfortunately $PIPESTATUS seems to be set after the invocation of the $PROMPT_COMMAND. Is there any trickery that I can use to access this information during the execution of $PROMPT_COMMAND?

  • This works for me: PROMPT_COMMAND='true | false | true; echo "${PIPESTATUS[@]}"' – Cyrus Oct 22 '14 at 15:10
  • Try this: PROMPT_COMMAND='echo "${PIPESTATUS[@]}"' and then run true | false | true – Jacobo de Vera Oct 22 '14 at 15:16
  • Now I understand your problem. But it works fine with my old Ubuntu 11.04. Output is: 0 1 0 – Cyrus Oct 22 '14 at 15:24
  • 1
    @JacobodeVera Doing exactly this works for me, as it should. Did you test exactly this? If not, what exactly are you doing, and what version of bash are you running? – Gilles Oct 22 '14 at 18:51
  • I was doing it wrong, see my comment in the answer below. Thanks for your help. – Jacobo de Vera Oct 23 '14 at 13:05
3

Commands within your prompt command function alter PIPESTATUS, bash saves and restores PIPESTATUS (and $?) after your prompt command, see the description of the intended behaviour here.

The trick is to save $PIPESTATUS[] (and/or $?) in the very first statement of your function, after that the original values are overwritten.

function myprompt() {
   _pipestatus=( "${PIPESTATUS[@]}" )
   echo "current: ${PIPESTATUS[@]}"
   echo "cached : ${_pipestatus[@]}"
}

PROMPT_COMMAND=myprompt

then:

$ true | false | true
current: 0
cached : 0 1 0

I do something similar to what you have described, but within a trap handler function for ERR rather than a prompt command.

  • Ah, of course! I was doing the same thing for the return code and forgot about it completely, then tried to capture PIPESTATUS way below, after doing other things. – Jacobo de Vera Oct 23 '14 at 10:37

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.