繁体   English   中英

在 bash 中使用 set -e / set +e 功能

[英]Using set -e / set +e in bash with functions

我一直在我的脚本中使用这样的简单 bash 序言:

#!/bin/bash
set -e

结合模块化/使用功能,今天这让我很苦恼。

所以,假设我有一个 function 之类的地方

foo() {
  #edit: some error happens that make me want to exit the function and signal that to the caller 
  return 2
}

理想情况下,我希望能够使用多个小文件,将它们的功能包含在其他文件中,然后像这样调用这些功能

set +e
foo
rc=$?
set -e

. 这恰好适用于两层例程。 但是如果 foo 也在调用这样的子例程,则返回之前的最后一个设置将set -e ,这将使脚本在返回时退出 - 我无法在调用 function 中覆盖它。 所以,我必须做的是

foo() {
  #calling bar() in a shielded way like above
  #..      

  set +e
  return 2
}

我觉得这很违反直觉(也不是我想要的——如果在某些情况下我想使用 function 而不屏蔽故障,而在其他情况下我想处理清理?)什么是最好的处理方法? 顺便提一句。 我在 OSX 上执行此操作,我尚未测试此行为在 Linux 上是否不同。

Shell函数实际上没有“返回值”,只是退出代码。

您可以将&& :添加到调用者,这会使命令“已测试”,并且不会退出它:

foo() {
    echo 'x'
    return 42
}

out=$(foo && :)
echo $out

:是“空命令”(即它没有做任何事情)。 在这种情况下,它甚至不会被执行,因为它只在foo返回0时才会运行(它没有)。

这输出:

x

它可以说有点难看,但是再一次,所有的shell脚本都可以说有点难看;-)

从FreeBSD引用sh(1) ,这比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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM