#!/usr/bin/env bash# Default parameters__name="Alice"# Non sub command_hello(){echo"hello $1!"}# sub commandsgreet(){_hello"$__name"}commands(){echo"$__subcommands"}help(){echo"Usage $0 <subcommand> [options]"echo""echo"Subcommands: $(commands)"}# Make sub command list__subcommands=$(set|grep-v"^_"|grep-v"^ "|grep" () $"|cut-d' '-f1|tr'\n'' ')# Start mainif[$#-eq0];thenhelpfi# Check sub command__subcommand="$1"shiftif!echo" $__subcommands "|grep-q" $__subcommand ";thenecho"$__subcommand is unknown subcommand."echo""helpexit1fi# Get other argumentswhilegetoptsn:hOPT;docase$OPTin"n")__name="$OPTARG";;"h")help;exit0;;*)echo"Unknown argument: $OPT";echo;help;exit1;;esacdone# Run sub command$__subcommand
こんな感じのスクリプト。
123456789101112131415161718192021
$ ./my_command.sh
Usage ./my_command.sh <subcommand> [options]
Subcommands: commands greet help
$ ./my_command.sh commands
commands greet help
$ ./my_command.sh help
Usage ./my_command.sh <subcommand> [options]
Subcommands: commands greet help
$ ./my_command.sh greet
hello Alice!
$ ./my_command.sh greet -n Bob
hello Bob!
$ ./my_command.sh abc
abc is unknown subcommand.
Usage ./my_command.sh <subcommand> [options]
Subcommands: commands greet help
$