Fish / par parser function option

It looks like work is currently underway to add support for this:

https://github.com/fish-shell/fish-shell/issues/478
https://github.com/xiaq/fish-shell/tree/opt-parse

But at the same time, what is the recommended way to deal with this? Should I just parse $ argv? If so, do you have any tips / best practices?

+5
source share
3 answers

I'm sure this is the best practice, but for now you can do something like this:

function options echo $argv | sed 's|--*|\\'\n'|g' | grep -v '^$' end function function_with_options for i in (options $argv) echo $i | read -l option value switch $option case a all echo all the things case f force echo force it case i ignore echo ignore the $value end end end 

Output:

 ➀ function_with_options -i thing -a --force ignore the thing all the things force it 
+5
source

You can do it:

 for item in $argv switch "$item" case -f --foo case -b --bar end end 

The above does not support writing short options to a single -fbz argument, the option values ​​are --foo=baz , --foo baz or f baz , the negative assignment is --name!=value , the end of the options -- and the dash - and -- are always part argument.

To solve these problems, I wrote a getopts function.

 getopts -ab1 --foo=bar baz 

Now let's look at the result.

 a b 1 foo bar _ baz 

The items on the left represent parameter flags or keys associated with the CLI. Elements on the right are parameter values. The underscore _ is the default key for keyless arguments.

Use read(1) to process the generated stream and switch(1) to match the patterns:

 getopts -ab1 --foo=bar baz | while read -l key option switch $key case _ case a case b case foo end end 

See the documentation.

+3
source

Parsing $argv is suitable for basic scenarios, but otherwise it can become tedious and error prone.

Before the fish had its own solution for argument analysis, the community created these plugins.

Starting with fish 2.7.0, you can use the parser of the built-in fish option: argparse

 function foo --description "Example argparse usage" set --local options 'h/help' 'n/count=!_validate_int --min 1' argparse $options -- $argv if set --query _flag_help printf "Usage: foo [OPTIONS]\n\n" printf "Options:\n" printf " -h/--help Prints help and exits\n" printf " -n/--count=NUM Count (minimum 1, default 10)" return 0 end set --query _flag_count; or set --local _flag_count 10 for i in (seq $_flag_count); echo foo; end end 

To see all possible argparse -h , run argparse -h or argparse --help .

+3
source

All Articles