Search code examples
linuxbashparentexit

Get exit status of the parent's last command


If I have a bash script that looks like this:

some_command
. some_bash

And some_bash that looks like this:

if [ "$?" != "0" ]
then
 do_something
else
 do_something_else
fi

I would expect that, some_bash, being executed in the parent's environment (.), would get the exit status ($?) of parent's some_command. But it doesn't. Im guessing it is getting an exit status of successfully calling itself, which is always true.

Is there any way to bypass this, other than some_bash $?and if [ "$1" != "0" ]?


Solution

  • Consider passing the value to the command:

    some_command
    . some_bash "$?"
    
    if [[ $1 -ne 0 ]]; then
    

    Although it would replace any positional parameter that currently exists.