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
If you are using
To combine them within a function in a manner that doesn't lose the values:
Run the above in
With a bit of precaution, this should work:
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: This answer is wrong, but interesting, so I'll leave it for future reference.
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 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:
Starting from the pipeline:
Here is a general solution using only POSIX shell and no temporary files:
Note the quotes around
This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually the exit status and not some string in a file.
you want the exit status from
Here is my solution:
Note: the child process inherits the open file descriptors from the parent. That means
If you worry that your
Step by step explanation of the construct:
From bottom up:
There are 3 common ways of doing this:
The first way is to set the
Bash also has an array variable called
You can use the 3rd command example to get the specific value in the pipeline that you need.
This is the most unwieldy of the solutions. Run each command separately and capture the status
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
If you have the moreutils package installed you can use the mispipe utility which does exactly what you asked.
lesmana's solution above can also be done without the overhead of starting nested subprocesses by using
I've checked this construct with dash version 0.5.5 and bash versions 3.2.25 and 4.2.42, so even if some shells don't support