Skip to content

Instantly share code, notes, and snippets.

@e7d
Last active December 10, 2023 10:45
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save e7d/e43e6586c1c2ecb67ae2 to your computer and use it in GitHub Desktop.
Save e7d/e43e6586c1c2ecb67ae2 to your computer and use it in GitHub Desktop.
Bash "try catch"
#!/bin/bash
export AnException=100
export AnotherException=101
# start with a try
try
( # open a subshell !!!
echo "do something"
[ someErrorCondition ] && throw $AnException
echo "do something more"
executeCommandThatMightFail || throw $AnotherException
throwErrors # automaticatly end the try block, if command-result is non-null
echo "now on to something completely different"
executeCommandThatMightFail
echo "it's a wonder we came so far"
executeCommandThatFailsForSure || true # ignore a single failing command
ignoreErrors # ignore failures of commands until further notice
executeCommand1ThatFailsForSure
local result = $(executeCommand2ThatFailsForSure)
[ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
executeCommand3ThatFailsForSure
echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
# now you can handle
case $ex_code in
$AnException)
echo "AnException was thrown"
;;
$AnotherException)
echo "AnotherException was thrown"
;;
*)
echo "An unexpected exception was thrown"
throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
;;
esac
}
#!/bin/bash
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
@RichardBronosky
Copy link

This is great!

@david-kariuki
Copy link

Great work!!

@rocapp
Copy link

rocapp commented Sep 19, 2020

This really is a great implementation! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment