Reputation: 1141
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" ]
?
Upvotes: 2
Views: 81
Reputation: 17188
You could export the exit status:
some_command
export LASTRETURN=$?
. some_bash
Inside some_bash you can use
${LASTRETURN}
Upvotes: 0
Reputation: 35405
You can write a function instead of a script and use it:
foo() {
if [ "$?" != "0" ]
then
do_something
else
do_something_else
fi
}
some_command
foo
You can define foo in some script, say script.sh. Then you can use it like:
. script.sh
some_command
foo
Upvotes: 0
Reputation: 75478
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.
Upvotes: 1