Last active
November 9, 2022 09:04
-
-
Save shaybensasson/00ff52aae7a2f06861ad175c818406a8 to your computer and use it in GitHub Desktop.
bash_script_with_try_catch.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# see https://stackoverflow.com/a/46597567/1640414 | |
echo "started" | |
function a() { | |
# do some stuff here | |
echo "a()" | |
ls *.sh | |
} | |
function b() { | |
# do more stuff here | |
echo "b()" | |
python --version & | |
PID=$! | |
} | |
# try | |
( | |
# this flag will make to exit from current subshell on any error | |
# inside it (all functions run inside will also break on any error) | |
# the `-x` just writes each command before running it (useful for logs|remove in prod env) | |
set -ex | |
a | |
b; echo "PID after b() is $PID" | |
echo 'r' | |
# do more stuff here | |
) | |
# catch | |
errorCode=$? | |
if [ $errorCode -ne 0 ]; then | |
echo "failed :(" | |
# We exit the all script with the same error, if you don't want to | |
# exit it and continue, just delete this line. | |
exit $errorCode | |
fi | |
echo "completed :)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment