Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

bash - syntax error: invalid arithmetic operator (error token is "")

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!

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 < "$1"
}
checkValidrecipe "$1"
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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your input file contains CR+LF line endings. As such, the variable ${line[4]} isn't a number like 10 but 10 which causes the error.

Remove carriage returns from the input file using a tool such as dos2unix.

Alternatively, you could change your script to handle it by modifying

done < "$1"

to

done < <(tr -d '
' < "$1")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...