【发布时间】:2016-08-21 11:53:01
【问题描述】:
在bash脚本中有什么用
set -e
?
我认为它与环境变量有关,但我之前没有遇到过
【问题讨论】:
-
阅读精美手册页的艺术变成了什么?
标签: bash
在bash脚本中有什么用
set -e
?
我认为它与环境变量有关,但我之前没有遇到过
【问题讨论】:
标签: bash
假设当前目录下脚本下面没有名为trumpet的文件:
#!/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.
您还可以将e 与x 选项结合使用,例如set -ex,其中:
-x 在执行时打印命令及其参数。
这可以帮助您调试 bash 脚本。
参考:Set Manpage
【讨论】:
引用help set
-e Exit immediately if a command exits with a non-zero status.
即脚本或外壳程序将在遇到任何以非 0(失败)退出代码退出的命令时立即退出。
任何失败的命令都会导致 shell 立即退出。
举个例子:
打开终端并输入以下内容:
$ set -e
$ grep abcd <<< "abc"
当您在grep 命令后按回车键时,shell 将退出,因为grep 以非 0 状态退出,即在文本 abc 中找不到正则表达式 abcd
注意:要取消设置此行为,请使用 set +e。
【讨论】:
man bash 说
如果一个简单的命令(参见上面的 SHELL GRAMMAR)以非零值退出,则立即退出 状态。如果失败的命令是命令列表的一部分,shell 不会退出 紧跟 while 或 until 关键字,if 语句中测试的一部分, && 或 │ 列表的一部分,或者如果命令的返回值正在通过 ! 反转。一种 如果设置了 ERR 陷阱,则会在 shell 退出之前执行。
如果您想避免测试 bash 脚本中每个命令的返回码,这是获得“快速失败”行为的超级方便的方法。
【讨论】: