如何从较低级别的函数中止鱼脚本?
问题描述:
鉴于鱼脚本foo.fish
,只有打印 “富”,帮助或错误如何从较低级别的函数中止鱼脚本?
function foo
__parse_args $argv[1]
echo foo
end
function __parse_args --argument option
if test -z $option
return # No option to parse, return early
end
switch $option
case -h --help
echo "Shows this help and exits"
return 0 # How can we exit 0 instead of return?
case -\*
echo "Error: '$option' not a valid option"
return 1 # How can we exit 1 instead of return?
end
end
实际行为:
↪ foo -h
Shows this help and exits
foo
预期的行为:
↪ foo -h
Shows this help and exits
的return
手册说它停止当前的内部函数并设置函数的退出状态。
如何在嵌套函数调用内提前退出脚本,并使用适当的退出代码?
请注意,我们不能使用exit
,因为它将退出shell而不仅仅是脚本。
答
除非通过source
或.
运行脚本,否则它将在其自己的新shell进程中运行。 exit
命令将终止该进程并返回到调用该脚本的父shell; exit
的参数将是退出后立即在该父进程中的$status
的值。
如果你实际上是(通过source
或.
或输入/粘贴在shell提示符下或通过定义它在你的.fishrc或启动文件放入〜/ .config或其他)定义在你的交互shell的foo
函数,那么__parse_args
无法从foo
返回。 foo
将必须显式检查返回值__parse_args
(即,在调用__parse_args
后检查$status
),然后在适当的情况下立即返回。这也意味着,在处理--help
时,最多__parse_args
返回不同的值比成功时返回的值更大。
然而,除非foo
实际操作中涉及一些修改你的shell环境,我建议使它成为一个可执行的脚本文件,而不是一个功能,例如,通过把它放到你的命令搜索$PATH
名为foo
地方文件:
#!/usr/bin/env fish
function foo
__parse_args $argv[1]
echo foo
end
function __parse_args --argument option
if test -z $option
return # No option to parse, return early
end
switch $option
case -h --help
echo "Shows this help and exits"
return 0 # How can we exit 0 instead of return?
case -\*
echo "Error: '$option' not a valid option"
return 1 # How can we exit 1 instead of return?
end
end
foo $argv
答
在__parse_args
,你可以为-h
返回1
,然后
function foo
__parse_args $argv[1]
or return $status
echo foo
end
这为-h
提供了非零返回状态,但这可能不是什么大不了的事情。
你是什么意思“退出shell而不是脚本”?除非您使用'source'或'.'来获取脚本,否则脚本将在其自己的shell中运行。 –