Last active
October 29, 2018 18:40
-
-
Save housni/d15288cdec75108ba39419450cab2bbb to your computer and use it in GitHub Desktop.
My Bash script starter template
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 | |
# See: https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html | |
# Set DEBUG to true for enhanced debugging: run prefixed with "DEBUG=true" | |
# Credits: https://github.com/ModusCreateOrg/devops-infra-demo | |
${DEBUG:-false} && set -o verbose; set -o xtrace | |
# Set CHECK to true to check script for syntax errors. | |
${CHECK:-false} && set -o noexec | |
# Any trap on ERR is inherited by shell functions, command substitutions, and | |
# commands executed in a subshell environment. The ERR trap is normally not | |
# inherited in such cases. | |
set -o errtrace | |
# Any trap on DEBUG and RETURN are inherited by shell functions, command | |
# substitutions, and commands executed in a subshell environment. The DEBUG and | |
# RETURN traps are normally not inherited in such cases. | |
set -o functrace | |
# Exit if any command exits with a non-zero exit status. | |
set -o errexit | |
# exit if script uses undefined variables. | |
set -o nounset | |
# prevent masking an error in a pipeline. | |
# | |
# look at the end of the 'Use set -e' section for an excellent explanation. | |
# see: https://www.davidpashley.com/articles/writing-robust-shell-scripts/ | |
set -o pipefail | |
# less eager word splitting - no space. | |
IFS=$'\n\t' | |
# Make debugging easier when you use `set -x` | |
# See: http://wiki.bash-hackers.org/scripting/debuggingtips#making_xtrace_more_useful | |
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' | |
usage() { | |
printf "USAGE:\n" | |
printf " %s ARG_1 [ARG_2] [ARG_3]\n\n" "$0" | |
} | |
do_something() { | |
local arg | |
arg="netstat" | |
# credits: https://stackoverflow.com/a/677212/379786 | |
command -v "${port_command}" >/dev/null 2>&1 || { echo >&2 "${port_command}: command not found."; exit 127; } | |
} | |
main() { | |
local required_arg | |
local optional_arg | |
local -i optional_int_arg | |
required_arg="${1:?'ERROR: Argument #1 is reuquired. Dontyaknow?'}" | |
optional_arg="${2:-foobar}" | |
optional_int_arg="${3:-8080}" | |
local result | |
result=$(do_something} | |
if [[ $result -eq 1 ]]; then | |
usage | |
printf "ERROR: Something could not be done!\n" | |
exit 1 | |
fi | |
} | |
main "$@" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment