2

Is there any way to a piped commands to replicate its previous command exit status?

For example:

#/bin/bash
(...)
function customizedLog() {
   # do something with the piped command output
   exit <returned value from the last piped comand/script (script.sh)>
}

script.sh | customizedLog
echo ${?} # here I wanna show the script exit value
(...)

I know I could simply check the return using ${PIPESTATUS[0]}, but I really want to do this like the customizedLog function wasn't there.

Any thoughts?

2 Answers 2

4

In bash:

set -o pipefail

This will return the last non-zero exit status in a pipeline, or zero if all commands in the pipeline succeed.

set -o pipefail
script.sh | customizedLog
echo ${?}

Just make sure customizedLog succeeds (return 0), and you should pick up the exit status of script.sh. Test with false | customizedLog and true | customizedLog.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not exactely what I was imagining but tottaly solved my issue! Thanks Jonathan
This is especially handy if multiple pipelines must be handled this way; as an ad-hoc solution the OP's own approach - even though he dismissed it - is worth reiterating: echo ${PIPESTATUS[0]} provides the same result without the need to change a global shell option (or, more simply, given that the first array element is being accessed, echo $PIPESTATUS.
2

script.sh | customizedLog

The above will run in two separate processes (or 3, actually -- customizedLog will run in a bash fork as you can verify with something like ps -T --forest). As far as I know, with the UNIX process model, the only process that has access to a process's return information is its parent so there's no way customized log will be able to retrieve it.

So no, unless the previous command is run from a wrapper command that passes the exit status through the pipe (e.g., as the last line):

( command ; echo $? ) | piped_command_that_is_aware_of_such_an_arrangement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.