bash算术求值和errexit陷阱

原文:https://www.technovelty.org//linux/bash-arithmetic-evaluation-and-errexit-trap.html

在 "traps for new players" 一章:

count=0
things="0 1 0 0 1"

for i in $things;
do
   if [ $i == "1" ]; then
       (( count++ ))
   fi
done

echo "Count is ${count}"

看上去非常正常?

我可能已经这么写好多次了。

但这是一个意想不到的错误:

((expression))
表达式按 ARITHMETIC EVALUATION 描写叙述的规则求值. 假设表达式的值非0。返回值为0; 否则返回值是1. 这个和let "expression"是同样的.

当你使用 -e或使能errexit运行该脚本时 -- 或许是因为脚本过大而变的不可信 -- count++ 将返回 0 (post-increment) 然后脚本就退出了. 这个陷阱须要注意!

原文地址:https://www.cnblogs.com/gcczhongduan/p/5342798.html