Last active
February 12, 2018 15:44
-
-
Save YakDriver/c4a1bb2c491c5838c58c24824524085c to your computer and use it in GitHub Desktop.
Bash Basics: Sorta try/catch/finally block
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 | |
# 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