Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Created February 14, 2018 15:27
Show Gist options
  • Save YakDriver/d5285a1d6f0f7b595240f508665e856d to your computer and use it in GitHub Desktop.
Save YakDriver/d5285a1d6f0f7b595240f508665e856d to your computer and use it in GitHub Desktop.
Bash Basics: A Robust try/catch/finally for shell scripts
#!/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
@nezed
Copy link

nezed commented Apr 3, 2020

  1. Don't forget to
    #!/bin/bash
    set -euo pipefail
    https://stackoverflow.com/a/2871034/10148424

  2. In cases when you don't need to handle error info
    finally() {}
    trap 'finally' EXIT
    is more elegant way
    https://stackoverflow.com/a/20085701/10148424

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