Bash“set -e”的功能是什么

What is the function of Bash “set -e”

本问题已经有最佳答案,请猛点这里访问。

在bash脚本中

1
set -e

我希望它与环境变量有关,但我以前没有遇到过。


引用help set

1
  -e  Exit immediately if a command exits with a non-zero status.

也就是说,一旦脚本或shell遇到任何用非0(失败)退出代码退出的命令,它就会退出。

任何失败的命令都将导致shell立即退出。

举个例子:

打开终端并键入以下内容:

1
2
$ set -e
$ grep abcd <<<"abc"

当你在grep命令后点击enter,shell就会退出,因为grep以非0状态退出,即在文本abc中找不到regex abcd

注意:要取消设置此行为,请使用set +e


man bash

Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero
status. The shell does not exit if the command that fails is part of the command list
immediately following a while or until keyword, part of the test in an if statement,
part of a && or ││ list, or if the command’s return value is being inverted via !. A
trap on ERR, if set, is executed before the shell exits.

如果您希望避免测试bash脚本中每个命令的返回代码,那么获得"快速失败"行为是非常方便的方法。


假设脚本下面的当前目录中没有名为arnum的文件:

1
2
3
4
5
6
7
8
#!/bin/bash
# demonstrates set -e
# set -e means exit immediately if a command exited with a non zero status

set -e
ls trumpet #no such file so $? is non-zero, hence the script aborts here
# you still get ls: cannot access trumpet: No such file or directory
echo"some other stuff" # will never be executed.

您也可以将ex选项(如set -ex)结合在一起,其中:

-x Print commands and their arguments as they are executed.

这可以帮助您调试bash脚本。

参考:设置手册页