-
-
Save progrium/6e47dbd5003e3e66675a to your computer and use it in GitHub Desktop.
playing around with a little bash subcommand environment
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 | |
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 $@ |
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
$ ./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