Call with no args
$ optparsing_demo
--verbose: false
--filename: myfile
positional:
Call with both short and long options, as well as positional args
$ optparsing_demo --verbose -f test.txt foo
--verbose: true
--filename: test.txt
positional: foo
Call with -- to pass positionals that look like flags
$ optparsing_demo --filename=test.txt -- -v --verbose -f --filename are acceptable options
--verbose: false
--filename: test.txt
positional: -v --verbose -f --filename are acceptable options
Called incorrectly with positionals before intended opts
$ optparsing_demo do not put positionals before opts --verbose --filename=mynewfile
--verbose: false
--filename: myfile
positional: do not put positionals before opts --verbose --filename=mynewfile
This method of opt parsing does not support flag chaining like getopt does
$ optparsing_demo -vh
optparsing_demo: Unknown option '-vh'
Call with no args
$ zparseopts_demo
--verbose:
--filename: myfile
positional:
Call with both short and long options, as well as positional args
$ zparseopts_demo --verbose -f test.txt foo
--verbose: --verbose
--filename: test.txt
positional: foo
Call with -- to pass positionals that look like flags
$ zparseopts_demo --filename test.txt -- -v --verbose -f --filename are acceptable options
--verbose:
--filename: test.txt
positional: -v --verbose -f --filename are acceptable options
Called incorrectly with positionals before intended opts. If you want this, zparseopts supports it with the -E flag.
$ zparseopts_demo do not put positionals before opts --verbose --filename=mynewfile
--verbose:
--filename: myfile
positional: do not put positionals before opts --verbose --filename=mynewfile
This method of opt parsing does supports flag chaining like getopt does
$ zparseopts_demo -vh
zparseopts_demo [-h|--help]
zparseopts_demo [-v|--verbose] [-f|--filename=<file>] [<message...>]
That's already what it does. In this example, -h/--help displays the contents of $usage, and without them the function executes - its execution just happens to also print output for demo purposes.
Yes, those are called positionals in this demo, and the contents are in "$@". Basically, zparseopts pulls out any -f/--flags that you've mapped and resets your argument array to what's left. If you want to mix positionals with flags (which I do not recommend, but others like), you want to use the
-E
option. Additionally, you can use subcommands like how thegit
command does by simply shifting off the first argument$1
, using that as a subcommand to determine further behavior with the remaining arguments in the arg array. That lets you do things likezparseopts_demo mysubcommand --foo --bar --baz positional1 positional2
etc. See https://zsh.sourceforge.io/Doc/Release/Zsh-Modules.html#index-zparseopts for further info.