views:

1363

answers:

3

I want to execute a long running command in bash shell, and both capture its exit status, and tee its output.

So I do this

command | tee out.txt
ST=$?

The problem is that the variable ST captures the exit status of tee and not of command. How can I solve this?

Note that command is long running and redirecting the output to a file to view it later is not a good solution for me.

+2  A: 

Dumb solution: Connecting them through a named pipe (mkfifo). Then the command can be run second.

 mkfifo pipe
 tee < pipe&
 command > pipe
EFraim
+3  A: 

If I am not wrong, there's an array that gives you the exit status of each command in a pipe. Let me see if I can find it, otherwise I will delete the answer.

Edit: yes

$ cat x| sed 's///'
cat: x: No such file or directory
$ echo $?
0
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo ${PIPESTATUS[*]}
1 0
$ touch x
$ cat x| sed 's'
sed: 1: "s": substitute pattern can not be delimited by newline or backslash
$ echo ${PIPESTATUS[*]}
0 1
Stefano Borini
Ooh, nice! All of them!
SamB
+13  A: 

There is a environment called $PIPESTATUS; It's an array that holds the exit status of your last foreground pipeline commands.

cODAR
works as advertised!
flybywire