6

I have bash code like this (Mac OS X):

foo.sh | tee foo.log echo $?

The problem is that $? contains the exit code of tee and not the exit code of foo.sh. How do I get the exit code of foo.sh?

1

2 Answers 2

7

The environment variable $PIPESTATUS is an array of exit statuses for all processes in a pipeline.

3
  • Why'd you ask the question if you know the answer?
    – phemmer
    Aug 12, 2012 at 19:36
  • 2
    Probably for the same reason there's a button to "answer your own question".
    – Skaperen
    Aug 12, 2012 at 20:03
  • @Patrick I didn't know the answer when I asked the question, but did some more digging and found it.
    – bluesmoon
    Aug 13, 2012 at 0:44
3

Also use a subshell:

tm@hoegaarden:~$ cat foo.sh
#!/bin/bash

echo "stuff and junk"

exit 123
tm@hoegaarden:~$ (./foo.sh ; echo $? > ./retval ) | tee output
stuff and junk
tm@hoegaarden:~$ cat retval 
123
1
  • This is more portable (not specific to bash) - hence upvote.
    – FooF
    Aug 14, 2012 at 8:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .