I have two processes foo and bar, connected with a pipe:
$ foo | bar
bar always exits 0; I'm interested in the exit code of foo. Is there any way to get at it?
|
|
If you are using
|
|||||||||||
|
|
This solution works without using bash specific features or temporary files. But it can only retrieve the exit status of one command in the pipe. Situation:
you want the exit status from Here is my solution:
Lets examine that step by step.
From bottom up:
Example:
Output:
|
||||
|
|
|
Starting from the pipeline:
Here is a general solution using only POSIX shell and no temporary files:
Note the quotes around |
||||
|
|
|
The following 'if' block will run only if 'command' succeeded:
Specifically speaking, you can run something like this:
Which will run Notice that pipes automatically clean themselves up; with the redirection you'll have to be carefull to remove "$haconf_out" when done. Not as elegant as |
||||
|
|
|
There are 3 ways of doing this. However your current setup should work. The reason here being that the grep won't match anything if the command fails, so grep will return with status PipefailThe first way is to set the
$PIPESTATUSBash also has a variable called
You can use the 3rd command example to get the specific value in the pipeline that you need. This solution might not be available though. I think Separate executionsThis is the most unwieldy of the solutions. Run each command separately and capture the status
|
|||||||||||||||||||
|
|
This is portable, i.e. works with any POSIX compliant shell, doesn't require the current directory to be writable, allows multiple scripts using the same trick to run simultaneously.
Edit: here is a stronger version following Gilles' comments:
|
|||||||||
|
|
What I do when possible is to feed the exit code from
Or if I know that the output from
This can always be done if there's some way of getting If
After this If you need to capture the output from
And, of course, there's the simple option of using a temporary file to store the status. Simple, but not that simple in production:
|
||||
|
|
|
While not exactly what you asked, you could use
so that your pipes return the last non zero return. might be a bit less coding Edit: Example
|
|||||||||||
|
|
EDIT: This answer is wrong, but interesting, so I'll leave it for future reference. Adding a ! to the command inverts the return code.
http://tldp.org/LDP/abs/html/exit-status.html
|
|||||||||||
|
|
With a bit of precaution, this should work:
|
|||||
|