Skip to content

Instantly share code, notes, and snippets.

@progrium
Last active Jan 20, 2017
Embed
What would you like to do?
playing around with a little bash subcommand environment
#!/bin/bash
cmd-hello() {
declare desc="Displays a friendly hello"
declare firstname="$1" lastname="$2"
echo "Hello, $firstname $lastname."
}
cmd-help() {
declare desc="Shows help information for a command"
declare command="$1" showsource="${2:-true}"
if [[ "$command" ]]; then
echo "$command $(extract-args $command)"
echo " $(extract-desc $command)"
echo
if [[ "$showsource" = "true" ]]; then
type cmd-$command | tail -n +2
echo
fi
else
echo; for cmd in $(list-cmds); do cmd-help $cmd false; done
fi
}
extract-args() {
local line=$(type cmd-$1 | grep declare | grep -v "declare desc" | head -1)
echo -e "${line// /\n}" | awk -F= '/=/{print "<"$1">"}' | tr "\n" " "
}
extract-desc() {
eval "$(type cmd-$1 | grep desc | head -1)"; echo $desc
}
list-cmds() {
declare -F | grep "\-f cmd-" | awk -Fcmd- '{print $2}'
}
main() {
local cmd="$1"; shift || true
if type cmd-$cmd &> /dev/null; then
cmd-$cmd $@
else
echo "No such command: $cmd"
echo
echo "Available commands:"
list-cmds | sed "s/^/ /"
echo
exit 2
fi
}
main $@
$ ./prog
No such command:
Available commands:
hello
help
$ ./prog help
hello <firstname> <lastname>
Displays a friendly hello
help <command> <showsource>
Shows help information for a command
$ ./prog hello Jeff Lindsay
Hello, Jeff Lindsay.
$ ./prog help hello
hello <firstname> <lastname>
Displays a friendly hello
cmd-hello ()
{
declare desc="Displays a friendly hello";
declare firstname="$1" lastname="$2";
echo "Hello, $firstname $lastname."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment