Ambrish
Ambrish

Reputation: 3677

Capture exit status from function in shell script

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
$

Upvotes: 6

Views: 3401

Answers (2)

anubhava
anubhava

Reputation: 785128

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.

Upvotes: 6

Jimmix
Jimmix

Reputation: 6506

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; }

Upvotes: 1

Related Questions