0
点赞
收藏
分享

微信扫一扫

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

举报

相关推荐

0 条评论