I have two processes
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
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
The first way is to set the
Bash 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
This is the most unwieldy of the solutions. Run each command separately and capture the status
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
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 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:
With a bit of precaution, this should work:
Starting from the pipeline:
Here is a general solution using only POSIX shell and no temporary files:
Note the quotes around
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:
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
EDIT: This answer is wrong, but interesting, so I'll leave it for future reference.
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.
you want the exit status from
Here is my solution:
Lets examine that step by step.
From bottom up: