set -e, -u, -o, -x pipefail

2022-05-11  本文已影响0人  QXPLUS

文章出处:

The set lines

set -e
set -u
set -o pipefail
set -x

set -e

如果任何命令具有非零的退出状态,该选项指示 bash 立即退出。在所有广泛使用的通用编程语言中,未处理的运行时错误(无论是 Java 中抛出的异常、C 中的分段错误,还是 Python 中的语法错误)都会立即停止程序的执行;不执行后续行。

set -x

启用 shell 模式,将所有执行的命令都打印到终端。
这是 set -x 的典型用例:在执行每个命令时打印它可以帮助您可视化脚本的控制流。

set -u

影响变量。
除了 $*$@,对您之前未定义的任何变量的引用都是一个错误,并导致程序立即退出。
出于各种充分的理由,Python、C、Java 等语言的行为方式都相同。一个是错别字不会在您没有意识到的情况下创建新变量。

#!/bin/bash
firstName="Aaron"
fullName="$firstname Maxwell"
echo "$fullName"

set -o pipefail

此设置可防止管道中的错误被屏蔽。
如果管道中的任何命令失败,则该返回码将用作整个管道的返回码。默认情况下,即使成功,管道的返回码也是最后一条命令的返回码。

$ grep some-string /non/existent/file | sort
grep: /non/existent/file: No such file or directory
% echo $?
0
$ set -o pipefail
$ grep some-string /non/existent/file | sort
grep: /non/existent/file: No such file or directory
$ echo $?
2

Setting IFS

IFS 变量,代表内部字段分隔符

#!/bin/bash
IFS=$' '
items="a b c"
for x in $items; do
    echo "$x"
done

IFS=$'\n'
for y in $items; do
    echo "$y"
done
... will print out this:

a
b
c
a b c

这在使用 bash 数组时很明显:

#!/bin/bash
names=(
  "Aaron Maxwell"
  "Wayne Gretzky"
  "David Beckham"
)

echo "With default IFS value..."
for name in ${names[@]}; do
  echo "$name"
done

echo ""
echo "With strict-mode IFS value..."
IFS=$'\n\t'
for name in ${names[@]}; do
  echo "$name"
done

## 输出结果
With default IFS value...
Aaron
Maxwell
Wayne
Gretzky
David
Beckham

With strict-mode IFS value...
Aaron Maxwell
Wayne Gretzky
David Beckham
上一篇 下一篇

猜你喜欢

热点阅读