【发布时间】:2020-10-29 17:50:59
【问题描述】:
我收到此错误消息:line 12: 470 + : syntax error: operand expected (error token is "+ ")
最后我仍然得到 470 的答案,但此错误消息显示在输出中,我不明白为什么。谁能解释一下?
这是我的代码:
while IFS= read -r var
do
total=$(($total+$var))
done<"$input"
echo "The total is = $total";
echo
我每次的最终输出:
line 12: 470 + : syntax error: operand expected (error token is "+ ")
The total is = 470
【问题讨论】:
-
这是因为
$var在循环的最后一次迭代中为空。该文件可能以空行结尾 -
我不明白我如何更正它,我是否以不同的方式结束它?
-
你可以在使用前检查
$var是否为空 -
在空行的情况下(即
${var}未定义)您可以将${var}默认为0:${var:-0}