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

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

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

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

 

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

 

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

你可能感兴趣的文章
小程序TAB列表切换内容动态变化,scrollview高度根据内容动态获取
查看>>
swoole_table 实现原理剖析
查看>>
你需要知道面试中的10个JavaScript概念
查看>>
TiDB RC4 Release
查看>>
阿里云有对手了!CDN横评:腾讯云优势明显
查看>>
Ajax常用方法
查看>>
Glide 简单流程分析
查看>>
Hmily 2.0.3 发布,高性能异步分布式事务 TCC 框架
查看>>
烟花年下岁月
查看>>
Java源码阅读之HashMap - JDK1.8
查看>>
Docker 构建统一的前端开发环境
查看>>
一文让你了解大数据时代,你的真实处境
查看>>
Problems at works
查看>>
Dell服务器系统安装后无法正常进入系统
查看>>
深入理解asp.net里的HttpModule机制
查看>>
java基础学习_常用类03_StringBuffer类、数组高级和Arrays类、Integer类和Character类_day13总结...
查看>>
Asp.net MVC Session过期异常的处理
查看>>
python ThreadPoolExecutor线程池使用
查看>>
IPTABLES 规则(Rules)
查看>>
关于URL编码
查看>>