Dean Hiller
Dean Hiller

Reputation: 20200

reading return code from bash script to bash script?

I have the following snippet working such that my bash script exits early on failure

./gradlew clean build release
if [ $? -eq 0 ]
then
  echo "Successfully BUILT FAKE RELEASE"
else
  echo "BUILDING FAKE RELEASE FAILED"
  exit $?
fi

I see the failure log statement BUT my script that calls it continues on instead of exiting and in that script, I have pretty much the same code

./runAllTesting.sh
if [ $? -eq 0 ]
then
  echo "Successfully RAN ALL TESTING"
else
  echo "TESTING SYSTEM Failed(don't release this)"
  exit $?
fi

What am I doing wrong here? This is on 10.11.6 el capitan mac computer.

Upvotes: 1

Views: 1945

Answers (2)

Dario
Dario

Reputation: 2713

my script that calls it continues on

Yes, you should check your snippet‘s exit code in the calling script, then behave accordingly

if ! ./posted_snippet.sh; then
  exit
fi

In this way the top level exits, but loses the information about the error code which caused it to exit. It is often irrelevant, because error messages from posted_snippet.sh would make clear which test failed and why. However, if that error code has to be passed to the upper level, one could use the concise form

./posted_snippet.sh || exit $?

which is way better than if ./posted_snippet.sh; then :; else exit $?; fi.

What is crucial is that posted_snippet.sh should exit with the correct code, and it has already been pointed out in the comments that it doesn’t. Your last $? captures the exit code of echo, which is always 0. Here is a working version:

./runAllTesting.sh
test_result=$?
if [ $test_result -eq 0 ]; then
  echo "Successfully RAN ALL TESTING"
else
  echo "TESTING SYSTEM Failed(don't release this)"
  exit $test_result
fi

Upvotes: 3

0.sh
0.sh

Reputation: 2762

$? means what is the exit status of the last command that was executed. The last command that was executed is echo "TESTING SYSTEM Failed(don't release this)" and it ran successfully. What you were really doing after that echo statement was exit 0. The workaround is to save $? in a variable

./gradlew clean build release
readonly status=$?
if [[ $status -eq 0 ]];then
  echo "Successfully BUILT FAKE RELEASE"
else
  echo "BUILDING FAKE RELEASE FAILED"
  exit $status
fi

The above solution won't work if and only if you are executing the if conditional statement in a child process inside your script

Upvotes: 2

Related Questions