简体   繁体   中英

Fish Shell argparse Doing Something Very Unexpected

I'm running fish 3.1.0 on OS X 10.14.5.

I am new to fish and to argparse. I like them both.

The following simple test code:

#!/usr/local/bin/fish

function afoo 
    set -l options (fish_opt -s h -l help)
    set options $options (fish_opt -s m -l max --required-val)
    set options $options (fish_opt -s n -l nnn --optional-val)

    argparse $options -- $argv

    echo "max" $_flag_max
    echo "nnn" $_flag_nnn
end

Should create two switches m and n. m must take a value while n can take a value.

Here is a simple screen grab when testing that rudimentary function in Terminal's CLI:

[/usr/local/bin/fish 3.1.0] ~ afoo -m foo -n baz
max foo
nnn
[/usr/local/bin/fish 3.1.0] ~ afoo -mfoo -nbaz
max foo
nnn baz
[/usr/local/bin/fish 3.1.0] ~ 

Why does argparse not parse the space between the -n switch and its parameter but it does parse the space between the -m switch and its parameter?

This is driving me nuts. I've read the documentation a dozen times. What am I doing wrong?

PS The order of the switches doesn't matter.

Why does argparse not parse the space between the -n switch and its parameter but it does parse the space between the -m switch and its parameter?

The -n takes an optional parameter. Those have to, by getopt convention, be directly attached to the option argument.

Look at eg

echo never | grep --color never

This won't disable color, instead it will set color to auto (the default no-argument value) and look for the string "never". So it will show you "never" in red. Instead you'd have to use --color=never (or if it had a short option "-c" then "-cnever" would also be acceptable).

Argparse acts like the usual unix getopt(3) option parsing, which it also uses under the covers, because that's how the rest of the system acts.

This is because n/nnn=? has an optional parameter, whereas m/max= has a required one. Those strings are the output of your calls to fish_opt .

Non-option arguments are stored in $argv after a successful run of argparse . So your baz ends up in $argv .

Excellent, Thanks so very. very much.

If you're a newbie like me you can find more detail about what these answers point to by searching stack overflow for 'getopt space optional argument'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM