Created
February 14, 2018 15:27
-
-
Save YakDriver/d5285a1d6f0f7b595240f508665e856d to your computer and use it in GitHub Desktop.
Bash Basics: A Robust try/catch/finally for shell scripts
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 | |
# This script uses traps to create try/catch/finally functionality in shell scripts. | |
# | |
# OUTPUT: | |
# | |
# Hello! We're reporting live from script | |
# ./try_catch2.sh: line 23: badcommand: command not found | |
# ./try_catch2.sh: line 23: exiting with status 127 | |
# It's the end of the line | |
# | |
finally() { | |
local exit_code="${1:-0}" | |
echo "It's the end of the line" | |
exit "${exit_code}" | |
} | |
catch() { | |
local this_script="$0" | |
local exit_code="$1" | |
local err_lineno="$2" | |
echo "$0: line $2: exiting with status ${exit_code}" | |
finally $@ #important to call here and as the last line of the script | |
} | |
trap 'catch $? ${LINENO}' ERR | |
# this is the stuff you want to try | |
echo "Hello! We're reporting live from script" | |
badcommand | |
echo "You can't see this echo!" | |
finally #important to call here and as the last line of the catch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/a/20085701/10148424