LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Catch exit code before pipe in bash script? (http://www.linuxquestions.org/questions/linux-general-1/catch-exit-code-before-pipe-in-bash-script-944976/)

prl77 05-14-2012 09:31 PM

Catch exit code before pipe in bash script?
 
I have a bash script that runs a command and pipes its output to 'tee' which splits it into two log files for later parsing. I need to catch the exit code from the command right before piping. How?

Code:

/usr/bin/command1 parameter1 --option1 2>&1 | tee -a $LOG1 $LOG2
        if [ $? != 0 ]; then
                do some shit
        else
                do other shit
        fi

It appears that I'm catching the result of 'tee' and not of 'command1'.

Thanks,
prl77

PS. I'm going on vacation tomorrow, will respond back in a week.

catkin 05-14-2012 09:44 PM

The bash variable PIPESTATUS:
Quote:

An array variable (see Arrays) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).
Code:

c@CW8:~$ false | true | echo foo
foo
c@CW8:~$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]} ${PIPESTATUS[2]}
1 0 0


towheedm 05-14-2012 09:47 PM

Remember, '$?' always returns the exit status of the last command, in your case the 'tee' command. What you can do, is save the output of command1 to a var first. You must also save the exit status to another var first if tee must be executed before the conditionals.

Hope it points you in the right direction.

towheedm 05-14-2012 09:48 PM

Aha, PIPESTATUS, something new for me learn about.

prl77 05-24-2012 12:09 PM

Quote:

Originally Posted by catkin (Post 4678434)
The bash variable PIPESTATUS:
Code:

c@CW8:~$ false | true | echo foo
foo
c@CW8:~$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]} ${PIPESTATUS[2]}
1 0 0


This hit the spot. Thanks man!


All times are GMT -5. The time now is 12:35 AM.