Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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?

share|improve this question

13 Answers 13

up vote 77 down vote accepted

If you are using bash, you can use the PIPESTATUS array variable to get the exit status of each element of the pipeline.

$ false | true
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
1 0

If you are using zsh, they array is called pipestatus (case matters!) and the array indices start at one:

$ false | true
$ echo "${pipestatus[1]} ${pipestatus[2]}"
1 0

To combine them within a function in a manner that doesn't lose the values:

$ false | true
$ retval_bash="${PIPESTATUS[0]}" retval_zsh="${pipestatus[1]}" retval_final=$?
$ echo $retval_bash $retval_zsh $retval_final
1 0

Run the above in bash or zsh and you'll get the same results; only one of retval_bash and retval_zsh will be set. The other will be blank. This would allow a function to end with return $retval_bash $retval_zsh (note the lack of quotes!).

share|improve this answer
And pipestatus in zsh. Unfortunately other shells don't have this feature. – Gilles Jun 2 '11 at 21:05
Note: Arrays in zsh begin counterintuitively at index 1, so it's echo "$pipestatus[1]" "$pipestatus[2]". – Legate Nov 14 '11 at 14:09
You could check the whole pipeline like this: if [ `echo "${PIPESTATUS[@]}" | tr -s ' ' + | bc` -ne 0 ]; then echo FAIL; fi – l0b0 Sep 25 '12 at 15:39
@JanHudec: Perhaps you should read the first five words of my answer. Also kindly point out where the question requested a POSIX-only answer. – camh Dec 16 '14 at 8:27
@JanHudec: Nor was it tagged POSIX. Why do you assume the answer must be POSIX? It was not specified so I provided a qualified answer. There is nothing incorrect about my answer, plus there are multiple answers to address other cases. – camh Dec 17 '14 at 9:15

There are 3 common ways of doing this:


The first way is to set the pipefail option (ksh, zsh or bash). This is the simplest and what it does is basically set the exit status $? to the exit code of the last program to exit non-zero (or zero if all exited successfully).

# false | true; echo $?
# set -o pipefail
# false | true; echo $?


Bash also has an array variable called $PIPESTATUS ($pipestatus in zsh) which contains the exit status of all the programs in the last pipeline.

# true | true; echo "${PIPESTATUS[@]}"
0 0
# false | true; echo "${PIPESTATUS[@]}"
1 0
# false | true; echo "${PIPESTATUS[0]}"
# true | false; echo "${PIPESTATUS[@]}"
0 1

You can use the 3rd command example to get the specific value in the pipeline that you need.

Separate executions

This is the most unwieldy of the solutions. Run each command separately and capture the status

# OUTPUT="$(echo foo)"
# printf '%s' "$OUTPUT" | grep -iq "bar"
0 1
share|improve this answer
Darn! I was just gonna post about PIPESTATUS. – slm Apr 21 '13 at 13:57
For reference there are several other techniques discussed in this SO question:… – slm Apr 21 '13 at 14:00
@Patrick the pipestatus solution is works on bash , just more quastion in case I use ksh script you think we can find something similar to pipestatus ? , ( meenwhile I see the pipestatus not supported by ksh ) – yael Apr 21 '13 at 14:32
@yael I don't use ksh, but from a brief glance at it's manpage, it doesn't support $PIPESTATUS or anything similar. It does support the pipefail option though. – Patrick Apr 21 '13 at 15:30
Great answer. I learned 2 things I never knew. :) – Tim Kennedy Apr 30 '13 at 19:14

While not exactly what you asked, you could use

#!/bin/bash -o pipefail

so that your pipes return the last non zero return.

might be a bit less coding

Edit: Example

[root@localhost ~]# false | true
[root@localhost ~]# echo $?
[root@localhost ~]# set -o pipefail
[root@localhost ~]# false | true
[root@localhost ~]# echo $?
share|improve this answer
set -o pipefail inside the script should be more robust, e.g. in case someone executes the script via bash – maxschlepzig Jun 3 '11 at 9:17
How does that work? do you have a example? – Johan Jun 8 '11 at 18:40
This works perfectly for me; I agree that it's more robust than the accepted solution insofar as you don't have to worry about indexes and making sure that you check the exit status on all your commands. Rather, you can simply run the pipe through bash -o pipefail -c "false | true" and if any piped command fails, echo $? will show it. – tobias.mcnulty Apr 24 '12 at 14:55
Note that -o pipefail is not in POSIX. – scy Jan 25 '13 at 15:15
This does not work in my BASH 3.2.25(1)-release. At the top of /tmp/ff I have #!/bin/bash -o pipefail. Error is: /bin/bash: line 0: /bin/bash: /tmp/ff: invalid option name – Felipe Alvarez Mar 24 '14 at 6:01

What I do when possible is to feed the exit code from foo into bar. For example, if I know that foo never produces a line with just digits, then I can just tack on the exit code:

{ foo; echo "$?"; } | awk '!/[^0-9]/ {exit($0)} {…}'

Or if I know that the output from foo never contains a line with just .:

{ foo; echo .; echo "$?"; } | awk '/^\.$/ {getline; exit($0)} {…}'

This can always be done if there's some way of getting bar to work on all but the last line, and pass on the last line as its exit code.

If bar is a complex pipeline whose output you don't need, you can bypass part of it by printing the exit code on a different file descriptor.

exit_codes=$({ { foo; echo foo:"$?" >&3; } |
               { bar >/dev/null; echo bar:"$?" >&3; }
             } 3>&1)

After this $exit_codes is usually foo:X bar:Y, but it could be bar:Y foo:X if bar quits before reading all of its input or if you're unlucky. I think writes to pipes of up to 512 bytes are atomic on all unices, so the foo:$? and bar:$? parts won't be intermixed as long as the tag strings are under 507 bytes.

If you need to capture the output from bar, it gets difficult. You can combine the techniques above by arranging for the output of bar never to contain a line that looks like an exit code indication, but it does get fiddly.

         { { foo; echo foo:"$?" >&3; } |
           { bar | sed 's/^/^/'; echo bar:"$?" >&3; }
         } 3>&1)
foo_exit_code=${output#*${nl}foo:}; foo_exit_code=${foo_exit_code%%$nl*}
bar_exit_code=${output#*${nl}bar:}; bar_exit_code=${bar_exit_code%%$nl*}
output=$(printf %s "$output" | sed -n 's/^\^//p')

And, of course, there's the simple option of using a temporary file to store the status. Simple, but not that simple in production:

  • If there are multiple scripts running concurrently, or if the same script uses this method in several places, you need to make sure they use different temporary file names.
  • Creating a temporary file securely in a shared directory is hard. Often, /tmp is the only place where a script is sure to be able to write files. Use mktemp, which is not POSIX but available on all serious unices nowadays.
foo_ret_file=$(mktemp -t)
{ foo; echo "$?" >"$foo_ret_file"; } | bar
foo_ret=$(cat "$foo_ret_file"; rm -f "$foo_ret_file")
share|improve this answer
When using the temporary file approach I prefer to add a trap for EXIT that removes all temporary files so that no garbage will be left even if the script dies – miracle173 Oct 16 '13 at 20:16

Starting from the pipeline:

foo | bar | baz

Here is a general solution using only POSIX shell and no temporary files:

exec 4>&1
error_statuses="`((foo || echo "0:$?" >&3) |
        (bar || echo "1:$?" >&3) | 
        (baz || echo "2:$?" >&3)) 3>&1 >&4`"
exec 4>&-

$error_statuses contains the status codes of any failed processes, in random order, with indexes to tell which command emitted each status.

# if "bar" failed, output its status:
echo "$error_statuses" | grep '1:' | cut -d: -f2

# test if all commands succeeded:
test -z "$error_statuses"

# test if the last command succeeded:
! echo "$error_statuses" | grep '2:' >/dev/null

Note the quotes around $error_statuses in my tests; without them grep can't differentiate because the newlines get coerced to spaces.

share|improve this answer

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.


someprog | filter

you want the exit status from someprog and the output from filter.

Here is my solution:

stdintoexitstatus() {
  read exitstatus
  return $exitstatus

((((someprog; echo $? >&3) | filter >&4) 3>&1) | stdintoexitstatus) 4>&1

echo $?

Example someprog and filter:

someprog() {
  echo "line1"
  echo "line2"
  echo "line3"
  return 42

filter() {
  while read line; do
    echo "filtered $line"

Example output:

filtered line1
filtered line2
filtered line3

Note: the child process inherits the open file descriptors from the parent. That means someprog will inherit open file descriptor 3 and 4. If someprog writes to file descriptor 3 then that will become the exit status. The real exit status will be ignored because stdintoexitstatus only reads once.

If you worry that your someprog might write to file descriptor 3 or 4 then it is best to close the file descriptors before calling someprog.

(((((exec 3>&- 4>&-; someprog); echo $? >&3) | filter >&4) 3>&1) | \
  stdintoexitstatus) 4>&1

The exec 3>&- 4>&- before someprog closes the file descriptor before executing someprog so for someprog those file descriptors simply do not exist.

Step by step explanation of the construct:

( ( ( ( someprog;          #part6
        echo $? >&3        #part5
      ) | filter >&4       #part4
    ) 3>&1                 #part3
  ) | stdintoexitstatus    #part2
) 4>&1                     #part1

From bottom up:

  1. A subshell is created with file descriptor 4 redirected to stdout. This means that whatever is printed to file descriptor 4 in the subshell will end up as the stdout of the entire construct.
  2. A pipe is created and the commands on the left (#part3) and right (stdintoexitstatus) are executed. stdintoexitstatus is also the last command of the pipe and that means the exit status of stdintoexitstatus will be the exit status of the entire construct.
  3. A subshell is created with file descriptor 3 redirected to stdout. This means that whatever is printed to file descriptor 3 in this subshell will end up in stdintoexitstatus and in turn will be the exit status of the entire construct.
  4. A pipe is created and the commands on the left (#part5 and #part6) and right (filter >&4) are executed. The output of filter is redirected to file descriptor 4. In #part1 the file descriptor 4 was redirected to stdout. This means that the output of filter is the stdout of the entire construct.
  5. Exit status from #part6 is printed to file descriptor 3. In #part3 file descriptor 3 was redirected to stdintoexitstatus. This means that the exit status from #part6 will be the final exit status for the entire construct.
  6. someprog is executed. The exit status is taken in #part5. The stdout is taken by the pipe in #part4 and forwarded to filter. The output from filter will in turn reach stdout as explained in #part4
share|improve this answer

If you have the moreutils package installed you can use the mispipe utility which does exactly what you asked.

share|improve this answer

With a bit of precaution, this should work:

foo-status=$(mktemp -t)
(foo; echo $? >$foo-status) | bar
foo_status=$(cat $foo-status)
share|improve this answer
How about to cleanup like jlliagre? Don't you leave a file behind called foo-status? – Johan Jun 8 '11 at 18:39
@Johan: If you prefer my suggestion, don't hesitate to vote it up ;) In addition not to leaving a file, it has the advantage of allowing multiple processes to run this simultaneously and the current directory need not to be writable. – jlliagre Jun 8 '11 at 20:40

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.

(foo;echo $?>/tmp/_$$)|(bar;exit $(cat /tmp/_$$;rm /tmp/_$$))

Edit: here is a stronger version following Gilles' comments:

(s=/tmp/.$$_$RANDOM;((foo;echo $?>$s)|(bar)); exit $(cat $s;rm $s))
share|improve this answer
This doesn't work for several reasons. 1. The temporary file may be read before it's written. 2. Creating a temporary file in a shared directory with a predictable name is insecure (trivial DoS, symlink race). 3. If the same script uses this trick several times, it'll always use the same file name. To solve 1, read the file after the pipeline has completed. To solve 2 and 3, use a temporary file with a randomly-generated name or in a private directory. – Gilles Jun 8 '11 at 23:00
+1 Well the ${PIPESTATUS[0]} is easier but the basic idea here do work if one know about the problems that Gilles mentions. – Johan Jun 9 '11 at 6:36
You can save a few subshells: (s=/tmp/.$$_$RANDOM;{foo;echo $?>$s;}|bar; exit $(cat $s;rm $s)). @Johan: I agree it's easier with Bash but in some contexts, knowing how to avoid Bash is worth it. – dubiousjim Aug 29 '12 at 22:25

The following 'if' block will run only if 'command' succeeded:

if command; then
   # ...

Specifically speaking, you can run something like this:


if haconf -makerw > "$haconf_out" 2>&1; then
   grep -iq "Cluster already writable" "$haconf_out"
   # ...

Which will run haconf -makerw and store its stdout and stderr to "$haconf_out". If the returned value from haconf is true, then the 'if' block will be executed and grep will read "$haconf_out", trying to match it against "Cluster already writable".

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 pipefail, but a legitimate alternative if this functionality is not within reach.

share|improve this answer

lesmana's solution above can also be done without the overhead of starting nested subprocesses by using { .. } instead (remembering that this form of grouped commands always has to finish with semicolons). Something like this:

{ { { { someprog; echo $? >&3; } | filter >&4; } 3>&1; } | stdintoexitstatus; } 4>&1

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 { .. } grouping, it is still POSIX compliant.

share|improve this answer

So I wanted to contribute an answer like lesmana's, but I think mine is perhaps a little simpler and slightly more advantageous pure-Bourne-shell solution:

# You want to pipe command1 through command2:
exec 4>&1
exitstatus=`{ { command1; printf $? 1>&3; } | command2 1>&4; } 3>&1`
# $exitstatus now has command1's exit status.

I think this is best explained from the inside out – command1 will execute and print its regular output on stdout (file descriptor 1), then once it's done, printf will execute and print command1's exit code on its stdout, but that stdout is redirected to file descriptor 3.

While command1 is running, its stdout is being piped to command2 (printf's output never makes it to command2 because we send it to file descriptor 3 instead of 1, which is what the pipe reads). Then we redirect command2's output to file descriptor 4, so that it also stays out of file descriptor 1 – because we want file descriptor 1 free for a little bit later, because we will bring the printf output on file descriptor 3 back down into file descriptor 1 – because that's what the command substitution (the backticks), will capture and that's what will get placed into the variable.

The final bit of magic is that first exec 4>&1 we did as a separate command – it opens file descriptor 4 as a copy of the external shell's stdout. Command substitution will capture whatever is written on standard out from the perspective of the commands inside it – but, since command2's output is going to file descriptor 4 as far as the command substitution is concerned, the command substitution doesn't capture it – however, once it gets "out" of the command substitution, it is effectively still going to the script's overall file descriptor 1.

(The exec 4>&1 has to be a separate command because many common shells don't like it when you try to write to a file descriptor inside a command substitution, that is opened in the "external" command that is using the substitution. So this is the simplest portable way to do it.)

You can look at it in a less technical and more playful way, as if the outputs of the commands are leapfrogging each other: command1 pipes to command2, then the printf's output jumps over command 2 so that command2 doesn't catch it, and then command 2's output jumps over and out of the command substitution just as printf lands just in time to get captured by the substitution so that it ends up in the variable, and command2's output goes on its merry way being written to the standard output, just as in a normal pipe.

Also, as I understand it, $? will still contain the return code of the second command in the pipe, because variable assignments, command substitutions, and compound commands are all effectively transparent to the return code of the command inside them, so the return status of command2 should get propagated out – this, and not having to define an additional function, is why I think this might be a somewhat better solution than the one proposed by lesmana.

Per the caveats lesmana mentions, it's possible that command1 will at some point end up using file descriptors 3 or 4, so to be more robust, you would do:

exec 4>&1
exitstatus=`{ { command1 3>&-; printf $? 1>&3; } 4>&- | command2 1>&4; } 3>&1`
exec 4>&-

Note that I use compound commands in my example, but subshells (using ( ) instead of { } will also work, though may perhaps be less efficient.)

Commands inherit file descriptors from the process that launches them, so the entire second line will inherit file descriptor four, and the compound command followed by 3>&1 will inherit the file descriptor three. So the 4>&- makes sure that the inner compound command will not inherit file descriptor four, and the 3>&- will not inherit file descriptor three, so command1 gets a 'cleaner', more standard environment. You could also move the inner 4>&- next to the 3>&-, but I figure why not just limit its scope as much as possible.

I'm not sure how often things use file descriptor three and four directly – I think most of the time programs use syscalls that return not-used-at-the-moment file descriptors, but sometimes code writes to file descriptor 3 directly, I guess (I could imagine a program checking a file descriptor to see if it's open, and using it if it is, or behaving differently accordingly if it's not). So the latter is probably best to keep in mind and use for general-purpose cases.


For historical reasons, here is my original, not-portable-to-all-shells answer:

[EDIT] My bad, this does not work with bash because bash needs extra coddling when fiddling with file descriptors, I will update this as soon as I can. [/EDIT]

So I wanted to contribute an answer like lesmana's, but near as I can tell, mine is the simplest and most light-weight of the pure-Bourne-shell solutions:

# You want to pipe command1 through command2:
exitstatus=`command1 1>&3; printf $?` 3>&1 | command2
# $exitstatus now has command1's exit status.

Per the caveats lesmana mentions, it's possible that command1 will at some point end up using file descriptor 3, so to be more robust, you would do:

exitstatus=`(3>&- command1) 1>&3; printf $?` 3>&1 | command2

The subshell around command1 will inherit file descriptor 3 from the main shell, but that 3>&- will immediately close it (just within that subshell), so command1 gets a 'cleaner', more standard environment. Not sure how often things use file descriptor three directly – I think most of the time programs use syscalls that return not-used-at-the-moment file descriptors, but sometimes code writes to file descriptor 3 directly, I guess (I could imagine a program checking a file descriptor to see if it's open, and using it if it is, or behaving differently accordingly if it's not). So the latter is probably best to keep in mind and use for general-purpose cases.

share|improve this answer
Looks interesting, but I can't quite figure out what you expect this command to do, and my computer can't, either; I get -bash: 3: Bad file descriptor. – G-Man Jun 5 at 7:03
@G-Man Right, I keep forgetting bash has no idea what it's doing when it comes to file descriptors, unlike the shells I typically use (the ash that comes with busybox). I'll let you know when I think of a workaround that makes bash happy. In the meantime if you've got a debian box handy you can try it in dash, or if you've got busybox handy you can try it with the busybox ash/sh. – mtraceur Jun 5 at 12:09
@G-Man As to what I expect the command to do, and what it does do in other shells, is redirect stdout from command1 so it doesn't get caught by the command substitution, but once outside the command substitution, it goes drops fd3 back to stdout so it's piped as expected to command2. When command1 exits, the printf fires and prints its exit status, which is captured into the variable by the command substitution. Very detailed breakdown here:… Also, that comment of yours read as if it was meant to be kinda insulting? – mtraceur Jun 5 at 12:17
Where shall I begin?   (1) I’m sorry if you felt insulted.   “Looks interesting” was meant earnestly; it would be great if something as compact as that worked as well as you expected it to.  Beyond that, I was saying, simply, that I didn’t understand what your solution was supposed to be doing.  I’ve been working/playing with Unix for a long time (since before Linux existed), and, if I don’t understand something, that’s a red flag that, maybe, other people won’t understand it either, and that it needs more explanation (IMNSHO).  … (Cont’d) – G-Man Jun 6 at 3:14
(Cont’d) …  Since you “… like to think … that [you] understand just about everything more than the average person”, maybe you should remember that the objective of Stack Exchange is not to be a command-writing service, churning out thousands of one-off solutions to trivially distinct questions; but rather to teach people how to solve their own problems.  And, to that end, maybe you need to explain stuff well enough that an “average person” can understand it.  Look at lesmana’s answer for an example of an excellent explanation.  … (Cont’d) – G-Man Jun 6 at 3:15

EDIT: This answer is wrong, but interesting, so I'll leave it for future reference.

Adding a ! to the command inverts the return code.

# =========================================================== #
# Preceding a _pipe_ with ! inverts the exit status returned.
ls | bogus_command     # bash: bogus_command: command not found
echo $?                # 127

! ls | bogus_command   # bash: bogus_command: command not found
echo $?                # 0
# Note that the ! does not change the execution of the pipe.
# Only the exit status changes.
# =========================================================== #
share|improve this answer
I think this is unrelated. In your example, I want to know the exit code of ls, not invert the exit code of bogus_command – Michael Mrozek Jun 2 '11 at 22:13
I suggest to draw back that answer. – maxschlepzig Jun 3 '11 at 9:15
Well, it appears I'm an idiot. I've actually used this in a script before thinking it did what the OP wanted. Good thing I didn't use it for anything important – Falmarri Jun 8 '11 at 17:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.