Reputation: 2066
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?
Upvotes: 2
Views: 138
Reputation: 60067
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
Upvotes: 2
Reputation: 753990
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
.
Upvotes: 4