Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Bash Basics: A Robust try/catch/finally for shell scripts
# This script uses traps to create try/catch/finally functionality in shell scripts.
# Hello! We're reporting live from script
# ./ line 23: badcommand: command not found
# ./ 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"
echo "You can't see this echo!"
finally #important to call here and as the last line of the catch
Copy link

nezed commented Apr 3, 2020

  1. Don't forget to
    set -euo pipefail

  2. In cases when you don't need to handle error info
    finally() {}
    trap 'finally' EXIT
    is more elegant way

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