我想将 $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
最佳答案
两项改进:
- 无需循环
$argv
,您只需将多个参数传递给字符串过滤器
即可。 - 默认情况下,函数有自己的作用域,但您可以通过
--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/