Zsh: parse command-line options with zparseopts 0 ▲ Adam Johnson 1 day ago · Tech · hide · 0 comments Sometimes you want your shell scripts to take options, like --verbose or --help, along with any positional arguments. Handling options is fiddly to do by hand, with the traditional portable approach being a large block of code using a while loop, a case statement, and some shifts. Bash has the getopts builtin, but it only handles single-letter options, like -v. Zsh also has getopts, for compatibility, with the same limitation. Zsh has a better tool: zparseopts. It handles both short and long options, in one line of declarations. A simple example Here’s a script called caw, which prints a crow’s call. It takes one on/off option, -l or --loud, to capitalize the message: #!/usr/bin/env zsh # Caw like a crow. zparseopts -D -E -F -- \ {l,-loud}=flag_loud \ || exit 1 if (( $#flag_loud )); then message="CAW!" else message="Caw!" fi print $message Without the option, it caws normally: $ ./caw Caw! With the option, it caws loudly: $ ./caw --loud CAW! And unknown options are rejected: $ ./caw… No comments yet. Log in to reply on the Fediverse. Comments will appear here.