So I am writing a small script in zsh which can take multiple arguments. However, the users happen to pass arguments out-of-order. For example, this would be valid call to the script:
./logproc.sh --include /var/log --exclude-file-ext gz,bz --show-only
Now, I am able to use positional arguments like $1, $2 etc. to expect --include
first, then --exclude-file-ext
and so on. But users are calling the script like this:
./logproc.sh --show-only --exclude-file-ext gz,bz --include /var/log
or
./logproc.sh --exclude-file-ext gz,bz --show-only --include /var/log
With time, the requirement to add more features is increasing and the permutation and combination of figuring out which arguments were passed to the script are going to explode.
Is there a built-in tool in zsh or a command (an external tool which can be called in the script) which can be used to figure out the arguments that were sent to the script?
PS: I am looking for ZSH-specific solution.
Traditionally shell built-in command getopts
is used for handling script parameters. From your example it seems that you need support for long options (this is short option: -s
and this is long option --long
), but most shells, including zsh doesn't support long options in their implementation of getopts. If it is absolutely necessary to use POSIX compatible tool, various implementations of this, like getopts_long, already exists.
Most of the time another tool is availabe - GNU getopt
. This one support both options and is available on most Linux distributions by default. You can find exhaustive example with description in man pages getopt(1).
zparseopts
zsh have another option called zparseopts
. You can find description and more examples in documentation for zshmodules(1). Finally, here is the code snippet for your case:
#!/bin/zsh
zparseopts -E -D -- \
-include:=o_include \
-exclude-file-ext:=o_exclude \
-show-only=o_show
echo "include: ${o_include[2]}"
echo "exclude: ${o_exclude[2]}"
echo "show? ${o_show}"