someCommand 2>&1 | grep pattern &
How do I get the exit status of someCommand
?
PIPESTATUS
doesn't work because it's a background process.
I've found this link and it seems to work but only if I use it exactly that way. Simple echo
ing to the screen doesn't seem to work. I was wondering if it's possible to get the exit code without creating temporary files.
In bash you could do :
Example :
For piped foreground processes
In case of a script say testscript.sh which contains :
do
For piped background processes
Method 1: Using pipefail
For testscript.sh which contains :
Do
You get an the exit status 1 from which you conclude that the script failed.
Had
cat nonexistingfile
been removed you would have got:Disdvantage : pipefail will return a one for all exit code that is not specific to the command that failed
Method 2 : Source the shell script
Final Touch
If you suspect a single command to fail in a shell script,test script, you could do below :
Do
With a temp file
You can put the code that saves the content of PIPESTATUS in a temp file inside
{ ... }
and run it in background. This approach would be needed if we are interested in the exit code of more than one command in the pipeline:Without a temp file