如何从较低级别的函数中止鱼脚本?

问题描述:

鉴于鱼脚本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而不仅仅是脚本。

+1

你是什么意思“退出shell而不是脚本”?除非您使用'source'或'.'来获取脚本,否则脚本将在其自己的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 
+0

在示例脚本中,例如,将'return 0'更改为'exit 0',然后复制粘贴功能并执行'foo -h'。你运行它的shell将关闭。根据“出口”手册,它将退出(鱼)壳。只有在采购文件时调用exit才会跳过文件的其余部分,而不是退出shell本身。 – Dennis

+0

是的,但在提示符处复制和粘贴与“source”或“。”相同 - 您正在交互式shell中定义函数,然后运行该函数。 无法从'fish'中的多个函数调用级别退出。我建议把它制作成脚本。 –

+0

在'〜/ .config/fish/functions/foo.fish'处创建脚本仍然会退出shell。 – Dennis

__parse_args,你可以为-h返回1,然后

function foo 
    __parse_args $argv[1] 
     or return $status 
    echo foo 
end 

这为-h提供了非零返回状态,但这可能不是什么大不了的事情。