fish shell:filter $argv(轻量级/动态argparse)

k5ifujac  于 10个月前  发布在  Shell
关注(0)|答案(1)|浏览(89)

我想把$argv分成两个变量,一个是opts,另一个是其他变量。

function filter_opts
    set -l filtered_opts
    set -l new_argv

    for opt in $argv
        if string match -r -- '-.*' $opt
            set -a filtered_opts $opt
        else
            set -a new_argv $opt
        end
    end

    set -g argv $new_argv
    echo $filtered_opts
end

function test_filter 
    set -g argv $argv
    echo $argv
    set -l opts (filter_opts $argv)
    echo $opts
    echo $argv

    # prog1 $opts $argv
    # prog2 $argv
end

字符串
但是输出中有重复的过滤选项,并且没有修改$argv.:-(

$ test_filter Twilight Zone --test -t
Twilight Zone --test -t
--test -t --test -t
Twilight Zone --test -t


理想情况下,输出看起来像这样:

$ test_filter Twilight Zone --test -t
Twilight Zone --test -t
--test -t
Twilight Zone

ercv8c1e

ercv8c1e1#

两项改进:
1.没有必要在$argv上循环,您只需向string filter传递多个参数即可。
1.默认情况下,函数有自己的作用域,但您可以通过--no-scope-shadowing修改其调用者的作用域(请参见function docs
把这些想法放在一起:

function filter_opts --no-scope-shadowing
    set options (string match  -- '-*' $argv)
    set arguments (string match --invert -- '-*' $argv)
end

function test_filter 
    filter_opts $argv
    echo "Options: $options"
    echo "Arguments: $arguments"
end

test_filter Twilight Zone --test -t

字符串
这将产生:

Options: --test -t
Arguments: Twilight Zone


也不要错过argparse,这是鱼的argument parsing command

相关问题