bash 语法错误:无效的算术运算符(错误标记为“”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22481278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
syntax error: invalid arithmetic operator (error token is "")
提问by user2364312
I am trying to write a function the checks a text file, line by line, checking each field by certain cretirias, and then sums it all up. I am using the exact same way to sum each one of cretirias, but for the 4th one (in the code it will be time) I get the error in the title. I tried removing the line that sums the time and my code worked just fine, I have no clue what's wrong with the line and I'm pretty new to Bash. Every bit of help will be appreciated!
我正在尝试编写一个函数,逐行检查文本文件,按特定条件检查每个字段,然后将其汇总。我使用完全相同的方式对每个 cretirias 求和,但是对于第 4 个(在代码中是时间),我在标题中收到错误。我尝试删除总结时间的行,我的代码运行良好,我不知道该行有什么问题,而且我对 Bash 还很陌生。每一点帮助将不胜感激!
Here's the code:
这是代码:
#!/bin/bash
valid=1
sumPrice=0
sumCalories=0
veganCheck=0
sumTime=0
function checkValidrecipe
{
while read -a line; do
if (( ${line[1]} > 100 )); then
let valid=0
fi
if (( ${line[2]} > 300 )); then
let valid=0
fi
if (( ${line[3]} != 1 && ${line[3]} != 0 )); then
let valid=0
fi
if (( ${line[3]} == 1)); then
veganCheck=1
fi
let sumPrice+=${line[1]}
let sumCalories+=${line[2]}
let sumTime+=${line[4]}
done < ""
}
checkValidrecipe ""
if (($valid == 0)); then
echo Invalid
else
echo Total: $sumPrice $sumCalories $veganCheck $sumTime
fi
And I can assume that every input file will be in the following format:
我可以假设每个输入文件都采用以下格式:
name price calories vegancheck time
I am trying to run the script with this input file:
我正在尝试使用此输入文件运行脚本:
t1 50 30 0 10
t2 10 35 0 10
t3 75 60 1 60
t4 35 31 0 100
t5 100 30 0 100
(Blank line included)
(包括空行)
And here's the output:
这是输出:
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
Total: 270 186 1 0
Thank you very much for your help!
非常感谢您的帮助!
回答by devnull
Your input file contains CR+LF line endings. As such, the variable ${line[4]}
isn't a number like 10
but 10\r
which causes the error.
您的输入文件包含 CR+LF 行尾。因此,变量${line[4]}
不是数字,10
但10\r
会导致错误。
Remove carriage returns from the input file using a tool such as dos2unix
.
使用诸如dos2unix
.
Alternatively, you could change your script to handle it by modifying
或者,您可以更改脚本以通过修改来处理它
done < ""
to
到
done < <(tr -d '\r' < "")