diff --git a/SC2145.md b/SC2145.md index 5548681..2481fcc 100644 --- a/SC2145.md +++ b/SC2145.md @@ -24,25 +24,30 @@ If the intention is to provide each array element as a separate argument, put th ### Exceptions +Concatenating a string with an array can be used to make a command line interface with subcommands. + +To implement the subcommand interface, first pick a prefix like `subcommand_` below for the function names that implement the subcommands. Then protect the parsing of the subcommands by listing them in the patterns of a case statement. In the body of the case statement, a concatenation of the prefix with `"$@"` will invoke the subcommand function and pass the rest of the parameters to the function. + +For example: ```sh -command_foo() { +subcommand_foo() { echo "In foo" echo "\$1 == $1 == aaa" echo "\$2 == $2 == bbb" } -command_bar() { +subcommand_bar() { echo "In bar" } -command_baz() { +subcommand_baz() { echo "In baz" } main() { case "$1" in foo | bar | baz ) - command_"$@" + subcommand_"$@" ;; * ) printf "Error: %s\n" "Unrecognized command" @@ -52,3 +57,5 @@ main() { main foo aaa bbb ``` + +In the above example, inside the `main` function, the value of `"$@"` is `( foo aaa bbb ccc )`. The value of `subcommand_"$@"` after expanding is `( subcommand_foo aaa bbb ccc )`, which the shell interprets as a call to the `subcommand_foo` function. \ No newline at end of file