Last active
January 4, 2025 20:17
-
-
Save goulashsoup/29bf88aa66e6453211cc5064f9881023 to your computer and use it in GitHub Desktop.
Bash strict mode script
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
#!/usr/bin/env bash | |
# Proper error handling for bash also known as "Bash Strict Mode" | |
# Usage: source 'error_handling.sh' | |
# https://gist.github.com/robin-a-meade/58d60124b88b60816e8349d1e3938615 | |
# https://disconnected.systems/blog/another-bash-strict-mode/ | |
if [ -n "${DEBUG:-}" ]; then | |
set -x | |
fi | |
set -e -E -o pipefail -u | |
# set => Set or unset shell attributes. | |
# -e => Exit when one of the commands fails. | |
# -E => If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. | |
# -o pipefail => the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. | |
# -u => Treat unset variables and parameters as an error. | |
shopt -s inherit_errexit | |
# shopt => This builtin allows you to change additional shell optional behavior. | |
# -s inherit_errexit => If set, command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment. | |
error_on_line() { | |
local error_code=$? | |
echo "$0: Error on line $1: $BASH_COMMAND" | |
exit $error_code | |
} | |
trap 'error_on_line $LINENO' ERR # For errors print line and command. | |
export MSYS_NO_PATHCONV=1 # Disable path conversion in git bash. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment