Created
November 15, 2019 10:32
-
-
Save simonfxr/034f21e922ec6f2866c26943b3c2f422 to your computer and use it in GitHub Desktop.
Simple multi command bash scripts
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 | |
SELF=$(basename "${BASH_SOURCE[0]}") | |
describe() { | |
cat <<EOF | |
Some Descriptive words... | |
EOF | |
} | |
### Commands | |
cmd_foo() { | |
HELP=" | |
Do foo never forget to do before bar | |
SOME PROSA | |
BLAH | |
" | |
echo "FOO CMD" | |
} | |
cmd_bar() { | |
HELP=" | |
Barify ARGS | |
" | |
echo "BAR" | |
} | |
### Generic stuff | |
__main() { | |
(( $# > 0 )) || { | |
printf 'Error: missing command argument\n\n' | |
cmd_help | |
exit 1 | |
} >&2 | |
cmd="cmd_${1}" | |
if [[ $(type -t "$cmd") != 'function' ]]; then | |
{ | |
printf 'Error: no command named %s\n\n' "$1" | |
cmd_help | |
exit 1 | |
} >&2 | |
else | |
"$cmd" "${@:2}" | |
fi | |
} | |
cmd_help() { | |
HELP=" | |
Print this message | |
" | |
echo "Usage: $SELF COMMAND ARG..." | |
echo "" | |
describe | |
echo "" | |
echo "List of available commands: " | |
echo "" | |
# shellcheck disable=SC2034 | |
declare -F | while read -r _declare _flag cmd; do | |
shopt -s extglob | |
[[ $cmd = cmd_* ]] || continue | |
unset HELP | |
eval "$(type "$cmd" | awk '/^ *HELP="/, /^";/ { print; } /^";/ { exit 0}')" | |
HELP="${HELP#$'\n'}" | |
help_lns=( ) | |
readarray -t help_lns <<<"${HELP%$'\n'}" | |
printf ' %-8s %s\n' "${cmd//cmd_/}" "${help_lns[0]}" | |
for ln in "${help_lns[@]:1}"; do | |
printf ' %8s %s\n' '' "${ln%%+([[:space:]])}" | |
done | |
echo "" | |
done | |
} | |
__main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment