Created
May 24, 2022 14:57
-
-
Save adamcin/9432239c4fa8d25cd883a0f3e108a7e8 to your computer and use it in GitHub Desktop.
bash_starter.sh
This file contains hidden or 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 | |
# Template for a multi-command bash script with online help by convention | |
# based on $0-dispatch pattern described here: | |
# https://www.oilshell.org/blog/2020/02/good-parts-sketch.html#the-0-dispatch-pattern-solves-three-important-problems | |
set -o nounset | |
set -o pipefail | |
set -o errexit | |
__describe() { | |
echo "a global description for the tool" | |
} | |
__describe_help() { | |
echo "show global help or help <command> for details" | |
} | |
__help_help() { | |
echo "usage: $(basename "$0") help" | |
echo "" | |
echo " print the global usage help and exit" | |
echo "" | |
echo "usage: $(basename "$0") help <command>" | |
echo "" | |
echo " provide usage hep for <command>" | |
} | |
help() { | |
local cmd | |
if [[ "$#" -eq 0 ]]; then | |
"$0" _globalusage | |
else | |
cmd="$1" | |
shift | |
if declare -F | grep -q "^declare -f __help_${cmd}\$"; then | |
"$0" "__help_${cmd}" "$@" | |
else | |
echo "no help available for ${cmd} $*" | |
fi | |
fi | |
} | |
_globalusage() { | |
echo "$(basename "$0"): $("$0" __describe)" | |
echo "" | |
echo " usage: $(basename "$0") <command>" | |
echo "" | |
"$0" _listcommands | xargs -L 1 "$0" _describecommand | |
} | |
_listcommands() { | |
declare -F | sed -n 's/^declare -f \([^_]\)/\1/ip' | |
} | |
_describecommand() { | |
local cmd | |
local desc | |
desc="" | |
local spacing | |
spacing=" " # cool trick | |
if [ "$#" -gt 0 ]; then | |
cmd="$1" | |
shift | |
if declare -F | grep -q "^declare -f __describe_${cmd}\$" ; then | |
desc="$("$0" "__describe_${cmd}")" | |
fi | |
echo " ${cmd}${spacing:${#cmd}}${desc}" # cool trick, pt.2 | |
fi | |
} | |
if [ "$#" -eq 0 ]; then | |
help >&2 | |
exit 1 | |
fi | |
"$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment