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?

7

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

  • Why'd you ask the question if you know the answer? – Patrick Aug 12 '12 at 19:36
  • 2
    Probably for the same reason there's a button to "answer your own question". – Skaperen Aug 12 '12 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 '12 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
  • This is more portable (not specific to bash) - hence upvote. – FooF Aug 14 '12 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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