Skip to content

Instantly share code, notes, and snippets.

@torbiak
Created October 4, 2020 00:25
Show Gist options
  • Save torbiak/3c6c4293fb661c0c9e0f401ec3c532eb to your computer and use it in GitHub Desktop.
Save torbiak/3c6c4293fb661c0c9e0f401ec3c532eb to your computer and use it in GitHub Desktop.
A straightforward way to have subcommands that each handle their own command lines, in a bash script.
#!/bin/bash
set -euo pipefail
a() {
# TODO: parse options or whatever.
echo "a called with args:" "$@"
}
b() {
echo "b called with args:" "$@"
}
usage='usage: subcommands.sh [options] <command> <args> [then <command> <args>]...'
while getopts 'h' opt; do
case "$opt" in
h) echo "$usage"; exit 0;;
esac
done
shift $((OPTIND-1))
while [[ $# -gt 0 ]]; do
func=$1; shift
args=()
while [[ $# -gt 0 ]]; do
[[ "$1" == then ]] && shift && break
args+=($1)
shift
done
"$func" "${args[@]}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment