Skip to content

Instantly share code, notes, and snippets.

@shaybensasson
Last active November 9, 2022 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaybensasson/00ff52aae7a2f06861ad175c818406a8 to your computer and use it in GitHub Desktop.
Save shaybensasson/00ff52aae7a2f06861ad175c818406a8 to your computer and use it in GitHub Desktop.
bash_script_with_try_catch.sh
#!/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