Skip to content

Instantly share code, notes, and snippets.

@AlexFBP
Created July 3, 2020 05:02
Show Gist options
  • Save AlexFBP/d6d523927b47f19f2f711f7ab63fc50b to your computer and use it in GitHub Desktop.
Save AlexFBP/d6d523927b47f19f2f711f7ab63fc50b to your computer and use it in GitHub Desktop.
Tiny try/catch bash functions
#!/bin/bash
# Refer https://stackoverflow.com/a/25180186/3180052 for usage and credits
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
}
@AlexFBP
Copy link
Author

AlexFBP commented Jul 3, 2020

You can load this in your shell or CI/CD with ("long" form, I know it can be a single line)

URL=https://gist.githubusercontent.com/.../trycatch.sh # TODO: Replace with the right URL, by the "Raw" button
eval "$(curl "$URL")"

and then you can write something like:

...
try
(
  # Code that may throw an error
)
catch || {
  # Handle the error - Available here in $ex_code
  ...

  # Optional: You can rethrow the "exception" causing the script to exit if not caught
  throw $ex_code 
  ...
}

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