Search code examples
unixshellio-redirectionexitstatus

unix shell, getting exit code with piped child


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


Solution

  • 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