Mornor Mornor - 2 months ago 9
Bash Question

In a bash script, test error code from a called script

My bash script (

init.sh
) call another script (
script.sh
) and I want to test the error code from
script.sh
before doing any further action in
init.sh
.

I thought about testing it with
$?
, but it does not work

My
init.sh
is like the following:

#!/bin/bash
set -e
echo "Before call"
docker run -v $PWD:/t -w /t [command]
if [ $? == 1 ]; then
echo "Issue"
fi
echo "After call"


I only got the
Before call
from
stdout
and not the
After call
.

I know for a fact that if I execute
docker run -v $PWD:/t -w /t [command]
alone with wrong arguments, then
echo $?
will rightly display 1.

I was thinking that I do not catch the exit code from
scrip.sh
, but from somewhere else.

Any ideas?

Answer

You running the script with set -e. This means that if any command exits with a non zero status, bash will stop executing all subsequent lines. So here, if docker exits with status 1, the conditional that follows will not have a chance to run at all. Try this instead:

#!/bin/bash
set -e
echo "Before call"
if ! docker run -v $PWD:/t -w /t [command]; then
        echo "Issue"
fi
echo "After call"

This runs the command inside the if test which suppresses the effect of set -e I described above and gives you a chance to catch the error. Note this is will also catch all non-zero statuses, not just 1.