Capture exit status from function in shell script -


i have simple script.

test.sh

_execute_method () {   exit 1 }  _execute_method error_code=$? if [[ $error_code -eq 1 ]];   echo "got error"   exit 0 fi 

this script terminate when exit 1 executed inside function. want capture exit status function , handle in main script.

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

actual output:

$ sh test.sh  $ echo $? 1 $ 

actual output:

$ sh test.sh got error  $ echo $? 0 $ 

you need use return instead of exit inside function:

_execute_method () { return 1; }  _execute_method error_code=$? if [[ $error_code -eq 1 ]]; echo "got error"; fi 

exit terminate current shell. if have use exit put function in script or sub shell this:

declare -fx _execute_method _execute_method () { exit 1; }  ( _execute_method; ) error_code=$? if [[ $error_code -eq 1 ]]; echo "got error"; fi 

(..) execute function in sub-shell hence exit terminate sub-shell.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -