Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple bash subcommands. Each subcommand is implemented as a function. For example, `sub_funcname` is called for `funcname` subcommand.
#!/bin/sh
ProgName=$(basename $0)
sub_help(){
echo "Usage: $ProgName <subcommand> [options]\n"
echo "Subcommands:"
echo " bar Do bar"
echo " baz Run baz"
echo ""
echo "For help with each subcommand run:"
echo "$ProgName <subcommand> -h|--help"
echo ""
}
sub_bar(){
echo "Running 'bar' command."
}
sub_baz(){
echo "Running 'baz' command."
echo "First arg is '$1'."
echo "Second arg is '$2'."
}
subcommand=$1
case $subcommand in
"" | "-h" | "--help")
sub_help
;;
*)
shift
sub_${subcommand} $@
if [ $? = 127 ]; then
echo "Error: '$subcommand' is not a known subcommand." >&2
echo " Run '$ProgName --help' for a list of known subcommands." >&2
exit 1
fi
;;
esac
@stephen304

This comment has been minimized.

Copy link

stephen304 commented Oct 1, 2015

I made a thing based on this that I am using so I can create multiple base commands with sub commands without duplicating the logic code.

The idea is that you make a main file in path (~/bin) with the name of the command, then you define sub_* functions, then source the runsub file. That way, if I make more base commands with sub commands, they're organized by file and use the same logic code in runsub:

https://github.com/Stephen304/dotfiles/blob/master/bin/stephen304
https://github.com/Stephen304/dotfiles/blob/master/bin/lib/runsub

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.