Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)
使用非官方的严格模式 (除非你喜欢debug)
对原作者表示尊重:(http://redsymbol.net/articles/unofficial-bash-strict-mode/)
核心是在脚本中采用这样的头部:
#! /bin/bash
set -euo pipefail
IFS=$'\n\t'
目的是让脚本变得更加健壮,让一下模糊的,不确定的,隐形的错误,显示出来,利于更好的控制
set -e
这个参数设定,但命令返回非0时退出脚本。意思是在脚本中对出现的错误进行零容忍。
但是有时候,可能在脚本中执行一些期望报错的命令,该怎么办呢?可以这样:
# "grep -c" reports the number of matching lines. If the number is 0,
# then grep's exit status is 1, but we don't care - we just want to
# know the number of matches, even if that number is zero.
# Under strict mode, the next line aborts with an error:
count=$(grep -c some-string some-file)
# But this one behaves more nicely:
count=$(grep -c some-string some-file || true)
echo "count: $count"
可以让这行命令不报错。
当然也可以临时性的去掉-e模式,
这样:
# We had started out this script with set -e . And then...
set +e
count=$(grep -c some-string some-file)
retval=$?
set -e
# grep's return code is 0 when one or more lines match;
# 1 if no lines match; and 2 on an error. This pattern
# lets us distinguish between them.
echo "return value: