linux - bash 从函数内部退出脚本

标签 linux bash

有些情况下您希望从函数内部终止脚本:

function die_if_fatal(){
    ....
    [ fatal ] && <termination statement>
}

如果脚本是来源的,$。脚本,终止语句为:

  • return,正如预期的那样,将从die 返回,但不会完成脚本
  • exit 终止 session (不返回脚本)。

现在,如果脚本被执行:chmod +x script; ./脚本:

  • return,正如预期的那样,将从die 返回,但不会完成脚本
  • exit 不会返回到 die 并终止脚本。

简单的方法是使用返回代码并在返回时检查它们,但是,我需要停止父进程,而不修改调用程序脚本。

有其他方法可以解决这个问题,但是,假设您在第 5 层进入一个复杂的脚本,并且您发现该脚本必须结束;也许是一个“神奇”的退出代码?我只想要源代码上的执行行为。

我正在寻找一个简单的语句来结束正在运行的源脚本。

采购时,从函数内部完成脚本的正确方法是什么?

最佳答案

假设您的脚本不会来自循环内部,您可以将脚本的主体包含在人工运行一次的循环中,并使用 break 命令中断脚本。

将这个想法形式化并提供一些支持实用程序,您的脚本必须具有以下结构:

#!/bin/bash

my_exit_code=''
bailout() {
    my_exit_code=${1:-0}

    # hopefully there will be less than 10000 enclosing loops
    break 10000
}

set_exit_code() {
    local s=$?
    if [[ -z $my_exit_code ]]
    then
        return $s
    fi
    return $my_exit_code
}

###### functions #######

# Define your functions here.
#
# Finish the script from inside a function by calling 'bailout [exit_code]'

#### end functions #####

for dummy in once;
do

    # main body of the script
    # 
    # finish the script by calling 'bailout [exit_code]'

done
set_exit_code

关于linux - bash 从函数内部退出脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399461/

相关文章:

c - 实现 Linux shell 时的 emacs

linux - 如何在自定义Linux(特别是树莓派)上添加启动屏幕

bash - 有人可以解释/给出这个 shell 参数替换的详细信息吗? ${cfg+-f "$cfg"}

linux - .Desktop 将命令行参数传递给 exec(类似于 shell 脚本)

linux - 如何在 Linux 中打印与我的排序结果相关的所有行

linux - 我可以/如何强制 micro-SD 卡进行 r/w 安装?

php - linux $PATH 对于同一个用户是不同的,取决于它的访问方式

python - nmap-python 无法在 Raspberry Pi 上正确安装

bash - 简化 bash 脚本?

bash - 自动解密并运行加密的 bash 脚本而不将解密的文件保存到文件系统