set -e 的作用

简介:
1
2
3
4
#!/bin/bash
set  -e
command  1command 2...
exit  0-----------------------

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

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.

你写的每个脚本都应该在文件开头加上set -e,这句语句告诉bash如果任何语句的执行结果不是true则应该退出。这样的好处是防止错误像滚雪球般变大导致一个致命的错误,而这些错误本应该在之前就被处理掉。如果要增加可读性,可以使用set -o errexit,它的作用与set -e相同。


Using -e gives you error checking for free. If you forget to check something, bash will do it for 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:

使用-e帮助你检查错误。如果你忘记检查(执行语句的结果),bash会帮你执行。不幸的是,你将无法检查$?,因为如果执行的语句不是返回0,bash将无法执行到检查的代码。你可以使用其他的结构:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[plain] view plain copy
command  
if  "$?" - ne  0];  then   
     echo  "command failed" ;   
     exit  1;   
fi   
could be replaced with
能够被代替为
[plain] view plain copy
command  || {  echo  "command failed" exit  1; }   
or
或者
[plain] view plain copy
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 || true, or if you have a longer section of code, you can turn off the error checking, but I recommend you use this sparingly.

如果你有一个命令返回非0或者你对语句执行的结果不关心,那你可以使用command || true,或者你有一段很长的代码,你可以关闭错误检查(不使用set -e),但是我还是建议你保守地使用这个语句。




 本文转自 sjfbjs 51CTO博客,原文链接:http://blog.51cto.com/11886896/1878719
相关文章
|
6月前
|
索引
集合--set
集合--set
39 0
|
1月前
|
存储 JavaScript 前端开发
set和map的区别
set和map的区别
46 4
|
2月前
|
存储 C++ 容器
在C++的set的作用类型
在C++的set的作用类型
10 0
|
7月前
|
算法 Swift
21 Set的定义和创建
Set的定义和创建
80 0
|
10月前
|
C#
C#属性的get与set
C#属性的get与set
|
11月前
|
存储 JavaScript
【ES6】Set 对象
【ES6】Set 对象
64 0
|
11月前
new Set与...new Set()的区别
new Set与...new Set()的区别,妙用多多
90 0
|
11月前
|
调度 C++ 容器
C++中set的用法
⭐一、set的简介 set的中文译为集合,知名见其意,因此set容器也就具有集合的属性啦!而集合这个概念大家应该上数学课应该都是学过的哈,集合它具有确定性、互异性、无序性。当然我们这里重点记住它的互异性就OK了,那么什么是互异性呢?就是说一个集合里边是不会出现两个甚至以上相同的元素的(有我没他,有他没我),说明集合还是比较专一的哈,大家以后对待感情也要专一哦!😉😉😉 还有非常重要的一点就是set容器会自动地对元素进行升序排序(从小到大)
250 0
手动实现es6的set集合 模拟set集合实现对应的功能
手动实现es6的set集合 模拟set集合实现对应的功能
|
C#
get和set访问器
get和set访问器
211 0