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

简介:

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将无法执行到检查的代码。你可以使用其他的结构:

 copy

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

或者

 copy

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

相关文章
|
4天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
30 3
|
1天前
|
监控 Shell 应用服务中间件
第十二章 Shell脚本编写及常见面试题(二)
第十二章 Shell脚本编写及常见面试题(二)
|
1天前
|
监控 关系型数据库 Shell
第十二章 Shell脚本编写及常见面试题(一)
第十二章 Shell脚本编写及常见面试题(一)
|
2天前
|
监控 Shell
生产环境Shell脚本Ping监控主机是否存活(多种方法)
生产环境Shell脚本Ping监控主机是否存活(多种方法)
|
2天前
|
运维 Shell
Shell脚本判断IP是否合法性(多种方法)
Shell脚本判断IP是否合法性(多种方法)
|
3天前
|
Linux Shell Android开发
自动化脚本之GPIO/LED相关适用于Android/Linux
自动化脚本之GPIO/LED相关适用于Android/Linux
13 0
|
8天前
|
运维 监控 Shell
利用Shell脚本编写局域网监控软件:实时监测主机连接情况
本文介绍了如何使用Shell脚本创建一个局域网监控工具,以实时检查主机连接状态。脚本包括扫描IP地址范围检测主机可达性及使用`netstat`监控ESTABLISHED连接。此外,还展示了如何每60秒将连接数数据自动提交到指定网站API,以便实时跟踪网络活动。这个自动化监控系统有助于提升网络安全性和故障排查效率。
32 0
|
9天前
|
Shell
Shell脚本之流程控制语句
Shell脚本之流程控制语句
|
10天前
|
JSON 运维 监控
训练shell常用脚本练习(三)
【4月更文挑战第14天】shell代码训练(三)
31 1
|
13天前
|
存储 弹性计算 Shell
ecs服务器shell常用脚本练习(十)
【4月更文挑战第11天】shell代码训练(十)
143 0