2010年11月2日星期二

在linux bash 中, “set -e” 的作用

简单来说就是保证脚本文件里每个命令都得到有效的执行,如果有问题,则会报错。
确保每个执行的命令都不返回false。
一般放在bash脚本的最开头。

可以帮助debug。


from "info bash":

Exit immediately if a simple command (*note Simple
Commands::) exits with a non-zero status, unless the command
that fails is part of an `until' or `while' loop, part of an
`if' statement, part of a `&&' or `||' list, or if the
command's return status is being inverted using `!'. A trap
on `ERR', if set, is executed before the shell exits.



The “set -e” option. This tells bash to exit the script if any statement returns a non-zero (false) value. You should put it at the beginning of the script as:

#! /bin/bash -e

or set -e

or set -o errexit

The “make benefit” is that you can avoid the situation of cumulative effect of errors becoming harder to debug.

However you can’t check $? shell variable as code won’t get there if it isn’t zero.

You can turn off this error checking for portions in the script by using:

set +e

command 1

command 2

command 3

set -e

Also, you can use :

command||true

if you want that this particular command’s non-zero return value shouldn’t exit the script.

Also, bash takes the status of last statement in a pipeline. false|true is true. To avoid this you can use:

set -o pipefail

没有评论:

发表评论