1

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.

2
  • 5
    I think $? in the exit parameter will always return success because the command preceding it is echo, which will always succeed Commented Dec 22, 2016 at 23:04
  • oh crap, lol, duh me. @KoCour Commented Dec 27, 2016 at 2:04

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

$? 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

2 Comments

so the value might not get overwritten
Overwritten by who?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.