mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Add explanatory text for the subcommand example
15
SC2145.md
15
SC2145.md
@@ -24,25 +24,30 @@ If the intention is to provide each array element as a separate argument, put th
|
|||||||
|
|
||||||
### Exceptions
|
### 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
|
```sh
|
||||||
command_foo() {
|
subcommand_foo() {
|
||||||
echo "In foo"
|
echo "In foo"
|
||||||
echo "\$1 == $1 == aaa"
|
echo "\$1 == $1 == aaa"
|
||||||
echo "\$2 == $2 == bbb"
|
echo "\$2 == $2 == bbb"
|
||||||
}
|
}
|
||||||
|
|
||||||
command_bar() {
|
subcommand_bar() {
|
||||||
echo "In bar"
|
echo "In bar"
|
||||||
}
|
}
|
||||||
|
|
||||||
command_baz() {
|
subcommand_baz() {
|
||||||
echo "In baz"
|
echo "In baz"
|
||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
case "$1" in
|
case "$1" in
|
||||||
foo | bar | baz )
|
foo | bar | baz )
|
||||||
command_"$@"
|
subcommand_"$@"
|
||||||
;;
|
;;
|
||||||
* )
|
* )
|
||||||
printf "Error: %s\n" "Unrecognized command"
|
printf "Error: %s\n" "Unrecognized command"
|
||||||
@@ -52,3 +57,5 @@ main() {
|
|||||||
|
|
||||||
main foo aaa bbb
|
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.
|
Reference in New Issue
Block a user