简体   繁体   中英

Bash piped commands and its returns

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?

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 false | customizedLog and true | customizedLog true | customizedLog .

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 (eg, as the last line):

( command ; echo $? ) | piped_command_that_is_aware_of_such_an_arrangement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM