views:

102

answers:

2

Let's say I do this in a unix shell

$ some-script.sh | grep mytext

$ echo $?

this will give me the exit code of grep

but how can I get the exit code of some-script.sh

EDIT

Assume that the pipe operation is immutable. ie, I can not break it apart and run the two commands seperately

+2  A: 

There are multiple solutions, it depends on what you want to do exactly.

The easiest and understandable way would be to send the output to a file, then grep for it after saving the exit code:

tmpfile=$(mktemp)
./some-script.sh > $tmpfile
retval=$?
grep mytext $tmpfile
rm tmpfile
watain
thanks for the response, see my edit
Mike
I see. Maybe that's a solution: `tmpfile=$(mktemp); (./some-script.sh; echo $? > $tmpfile) | grep mytext; retval=$(cat $tmpfile)`. That's quite dirty, but maybe it helps.
watain
then grep gets the output of `echo $? > tmpfile`
Mike
No, because `echo $? > $tmpfile` has no output. The standard output of `echo` is sent to `$tmpfile`.
watain
right, and that nothing gets passed to grep, it doesn't append the output of the first command
Mike
I'm not sure if I understood that correctly. The output of the first command (`./some-script.sh`) still reaches grep. Have you tried it? Maybe you could add the actual script with the problem and why the pipe operation is immutable.
watain
A: 

If you're using bash:

PIPESTATUS
    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). 
Randy Proctor
I'm using sh. My client doesn't like bash
Mike