似乎有一些工作正在进行中,以便在未来增加对此的支持:
https://github.com/fish-shell/fish-shell/issues/478
https://github.com/xiaq/fish-shell/tree/opt-parse
但与此同时,推荐的解决方法是什么?我应该解析$ argv吗?如果是这样,你有一些提示/最佳做法?
解析$argv对于基本方案而言是很好的选择,但否则可能变得乏味且容易出错。
在Fish有自己的参数解析解决方案之前,社区创建了这些插件
从fish 2.7.0开始,您可以使用fish的内置选项解析器: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
Run Code Online (Sandbox Code Playgroud)
要查看所有可能的结果,请运行argparse -h或argparse --help。
我注意到这是不是最好的做法,但在此期间你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
输出:
? function_with_options -i thing -a --force
ignore the thing
all the things
force it
Run Code Online (Sandbox Code Playgroud)