博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Unix/Linux shell脚本中 “set -e” 的作用
阅读量:6936 次
发布时间:2019-06-27

本文共 1638 字,大约阅读时间需要 5 分钟。

1
2
3
4
5
6
#!/bin/bash
set 
-e
command 
1
command 
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
command  
if 
"$?"
-
ne 
0]; 
then   
   
echo 
"command failed"
;   
   
exit 
1;   
fi


could be replaced with

能够被代替为


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

 说明:|| command未执行成功,则执行 { echo "command failed"; exit 1; }

or

或者

 

1
2
3
4
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),但是我还是建议你保守地使用这个语句。

本文转自 Mr_sheng 51CTO博客,原文链接:http://blog.51cto.com/sf1314/2062713

转载地址:http://mabnl.baihongyu.com/

你可能感兴趣的文章
高性能IOT服务器实现之路
查看>>
iOS混合开发库(GICXMLLayout)布局案例分析(2)闲鱼案例
查看>>
面试驱动技术 - KVO && KVC
查看>>
C、C++、Java、JavaScript、PHP、Python分别用来开发什么?
查看>>
测试格式
查看>>
Binder机制情景分析之linux环境适配
查看>>
209. Minimum Size Subarray Sum
查看>>
超级课程表API
查看>>
puppet客户端取消主动更新
查看>>
redis 3.0.7 安装部署
查看>>
如何查看mysql的用户及授权
查看>>
<Power Shell>新的征程
查看>>
【Android游戏开发之六】在SurfaceView中添加组件!!!!并且相互交互数据!!!!...
查看>>
SQLite操作
查看>>
安装Gogs及简单配置(使用默认数据库)
查看>>
奔向新纪元,Vista安装经历
查看>>
Centos7无法使用ssh登陆及解决方案
查看>>
应用强制访问控制管理网络服务
查看>>
Exchange 2013多租户托管PART 2:Exchange基本配置
查看>>
Mellanox发布升级版RoCE软件 简化以太网RDMA部署
查看>>