linux - [Solved-5 Solutions] Pipe output and capture exit status in Bash - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
If you need to execute a long running command in Bash, and both capture its exit status, and tee(command) its output.
command | tee out.txt
ST=$?
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 1:
- There is an internal Bash variable called $PIPESTATUS;
- It’s an array that holds the exit status of each command in your last foreground pipeline of commands.
<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
click below button to copy the code. By - Linux tutorial - team
It works with other shells (like zsh):
set -o pipefail
...
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 2:
Using bash's set -o pipefail
"pipefail: the return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status"
Linux - Solution 3:
mkfifo pipe
tee out.txt < pipe &
command > pipe
echo $?
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 4:
There's an array that gives exit status of each command in a pipe.
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo $?
0
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo ${PIPESTATUS[*]}
1 0
$ touch x
$ cat x| sed 's'
sed: 1: "s": substitute pattern can not be delimited by newline or backslash
$ echo ${PIPESTATUS[*]}
0 1
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 5:
- This solution works without using bash specific features or temporary files.
- In the end the exit status is actually the exit status and not some string in a file
Situation:
someprog | filter
click below button to copy the code. By - Linux tutorial - team
It you need the exit status from someprog and the output from filter.
You can use this:
((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1
echo $?