shell - fish shell : filter $argv (lightweight/dynamic argparse)

标签 shell fish

我想将 $argv 分成两个变量。一份包含选项,一份包含其他所有内容。

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

最佳答案

两项改进:

  1. 无需循环$argv,您只需将多个参数传递给字符串过滤器即可。
  2. 默认情况下,函数有自己的作用域,但您可以通过 --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 这是 fish 的 argument parsing command .

关于shell - fish shell : filter $argv (lightweight/dynamic argparse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77384651/

相关文章:

bash - 如何从makefile规则导出变量?

null - 如何在fish shell中隐藏多个命令输出?

linux - 在 fish shell 中定义一个别名

linux - 在 fish shell 中将 awk 输出设置为变量

linux - 有没有办法将环境变量设置为 x 小时

bash - 如何grep文件中不区分大小写的字符串?

linux - 脚本无法获取 "Not Valid Identifier"

linux - 如何在 shell 脚本中使用 line 作为可选函数?

python - 检查 pip 是否通过脚本安装

fish shell ;将配置导入主配置