Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Last active February 12, 2018 15:44
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 YakDriver/c4a1bb2c491c5838c58c24824524085c to your computer and use it in GitHub Desktop.
Save YakDriver/c4a1bb2c491c5838c58c24824524085c to your computer and use it in GitHub Desktop.
Bash Basics: Sorta try/catch/finally block
#!/bin/bash
# Shows the right and wrong ways of try/catch/finally blocks in shell scripting.
#
# OUTPUT:
#
# *Try* 1 (FAIL) ---------
# aaa
# bbb
# ./try_catch.sh: line 34: thisisabadcommand: command not found
# You shouldn't see this
# *Finally*
#
# *Try* 2 (FAIL) ---------
# aaa
# ./try_catch.sh: line 46: doesntcatchthisbadcommand: command not found
# You shouldn't see this before the catch
# ./try_catch.sh: line 48: thisisabadcommand: command not found
# *Catch*
# *Finally*
#
# *Try* 3 (SUCCESS) ---------
# aaa
# ./try_catch.sh: line 59: catchesthisbadcommand: command not found
# *Catch*
# *Finally*
#
# FAIL - this will not work as a TRY/CATCH
echo "*Try* 1 (FAIL) ---------"
{
echo aaa
echo bbb
thisisabadcommand
echo "You shouldn't see this"
} || {
echo *Catch*
}
echo *Finally*
echo
# FAIL - this enters "catch" but only because the final command is a problem
echo "*Try* 2 (FAIL) ---------"
{
echo aaa
doesntcatchthisbadcommand
echo "You shouldn't see this before the catch"
thisisabadcommand
} || {
echo *Catch*
}
echo *Finally*
echo
# SUCCESS - last echo in top block is never reached. Glue commands together with &&
echo "*Try* 3 (SUCCESS) ---------" &&
{
echo aaa &&
catchesthisbadcommand &&
echo "You shouldn't see this (and you won't)"
} || {
echo *Catch*
}
echo *Finally*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment