linux - Bash 函数忽略 set -e

标签 linux bash

如何将函数作为“测试命令”运行并在失败时执行操作,同时仍然在发生错误时立即中止该函数? 考虑以下脚本

#!/bin/bash -e

function foo() {
   echo Entering foo
   false
   echo Should not reach this line
}

foo || echo I want to see this line on failure in foo
foo

我得到的输出是

Entering foo
Should not reach this line
Entering foo

虽然我想得到

Entering foo
I want to see this line on failure in foo
Entering foo

我想我正在寻找的是一种将函数标记为未测试命令的方法。根据 bash 手册页

 -e errexit
         Exit immediately if any untested command fails in non-interactive
         mode.  The exit status of a command is considered to be explicitly
         tested if the command is part of the list used to control an if,
         elif, while, or until; if the command is the left hand operand of
         an “&&” or “||” operator; or if the command is a pipeline preceded
         by the ! operator.  If a shell function is executed and its exit
         status is explicitly tested, all commands of the function are con‐
         sidered to be tested as well.

编辑 预期的输出是错误的。为清楚起见对其进行了编辑

最佳答案

set -e 在第一次调用 foo 时被禁用,因为它位于 || 的左侧。

此外,你永远不会看到输出的 I want to see this ... 字符串,除非 foo 中的最后一个 echo 不知何故失败(是 foo 中的最后一个 echo 决定函数的退出状态)。

foo() {
    echo Entering foo
    false && echo Should not reach this line
}

foo || echo I want to see this line on failure in foo
foo

以上输出(带或不带set -x)

Entering foo
I want to see this line on failure in foo
Entering foo

现在 falsefoo 中最后执行的语句。

关于linux - Bash 函数忽略 set -e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785352/

相关文章:

linux - 使用 Bash 读取文件然后使用针对文件本身的行执行 "grep"

linux - BASH:找到字符串并打印上面的所有相关注释

linux - 在同一目录中移动多个文件而无需每次键入目录名称 (Linux)

c - 程序fork 4个子进程,每个子进程都会做不同的操作

linux - 有没有办法找到一个应用程序是否有供其他应用程序调用的接口(interface)

linux - Bash Shell 脚本远程后台处理

linux - 在 linux 中如何将多个文件归档和压缩为一个文件并删除源文件?

linux - 如何在 Shell 的循环中定义两个具有一对一关系的变量

linux - 如何删除文件名的这些部分?

bash - 多行 bash 注释礼仪 (#+)