加入收藏 | 设为首页 | 会员中心 | 我要投稿 上海站长网 (https://www.021zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

Unix/Linux 脚本中 “set -e” 的作用

发布时间:2022-12-15 13:39:57 所属栏目:Unix 来源:未知
导读: Unix/Linux 脚本中 "set -e" 的作用
example:
-----------------------------------------------------------
#!/bin/bash
set -e
command 1
command 2
...
-----------------------------

Unix/Linux 脚本中 "set -e" 的作用

example:

-----------------------------------------------------------

#!/bin/bash

set -e

command 1

command 2

...

----------------------------------------------------------

Use set -e

Every script you write should include set -e at the top. This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Using -e gives you error checking for free. If you forget to check something,bash will do it or you. Unfortunately it means you can't check $? as bash will never get to the checking code if it isn't zero. There are other constructs you could use:

commandif [ "$?"-ne 0]; then echo "command failed"; exit 1; fi

could be replaced with

command || { echo "command failed"; exit 1; }

or

if ! command; then echo "command failed"; exit 1; fi

What if you have a command that returns non-zero or you are not interested in its return value? You can use command || trueunix脚本, or if you have a longer section of code, you can turn off the error checking, but I recommend you use this sparingly.

(编辑:上海站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章