6

I have a very simple script.

test.sh

_EXECUTE_METHOD () {
  exit 1
}

_EXECUTE_METHOD
ERROR_CODE=$?
if [[ $ERROR_CODE -eq 1 ]]; then
  echo "Got error"
  exit 0
fi

This script terminate immediately when exit 1 executed inside the function. I want to capture this exit status from function and handle it in the main script.

I have tried set -e & set +e, still no success. I can not use return statement.

Actual output:

$ sh test.sh 
$ echo $?
1
$

Actual output:

$ sh test.sh
Got error 
$ echo $?
0
$
3
  • 4
    "I can not use return statement." - Yes, you can! Just try it. Commented Jul 30, 2015 at 9:18
  • There's a then missing after the semicolon. Also, [[ is nothing but a portability pitfall; [ should be used. Commented Jul 30, 2015 at 9:24
  • @Jens It is possible even to resign from using [ altogether. Example Commented Jan 19, 2022 at 3:10

2 Answers 2

6

You need to use return instead of exit inside the function:

_EXECUTE_METHOD () { return 1; }

_EXECUTE_METHOD || echo "Got error"

exit will terminate your current shell. If you have to use exit then put this function in a script or sub shell like this:

declare -fx _EXECUTE_METHOD
_EXECUTE_METHOD () { exit 1; }

_EXECUTE_METHOD || echo "Got error"

(..) will execute the function in a sub-shell hence exit will only terminate the sub-shell.

Sign up to request clarification or add additional context in comments.

3 Comments

Sub-shell (..), exit code capture ERROR_CODE=$? and Bash test [[ seem to be redundant.
Agreed though more verbosity is needed sometimes for better understanding. Even if..then..else can be shortened as in the updated answer now.
Just commenting to say that I fell down a rabbit hole with the "declare" built-in. Being it an advanced topic, it would be great if you could add more info as to why it is needed
1

No need for [[ or [

#!/bin/sh

set -eu

_EXECUTE_METHOD () {
  return 1
}

if ! _EXECUTE_METHOD; then
  echo "Got error"
  exit 0
fi

or if you want to be concise:

#!/bin/sh

set -eu

_EXECUTE_METHOD () {
  return 1
}

_EXECUTE_METHOD || { echo "Got error"; exit 0; }

1 Comment

never know this is possible in shell script. learn something new today

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.