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?

bluesmoon
  • 291
  • 1
  • 3
  • 8
  • http://stackoverflow.com/questions/6871859/piping-command-output-to-tee-but-also-save-exit-code-of-command – Devdas Aug 12 '12 at 18:39

2 Answers2

7

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

bluesmoon
  • 291
  • 1
  • 3
  • 8
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
Tom Maher
  • 31
  • 1