8

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!

Zivxx
  • 115
  • 1
  • 1
  • 5

1 Answers1

26

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.

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 '\r' < "$1")
devnull
  • 118,548
  • 33
  • 236
  • 227
  • Wow! Thank you for the fast response! And I used dos2unix on my script but not on the input files, so now after I used it on the input file it's working great. Thank you very much! Have a good day :) – Zivxx Mar 18 '14 at 13:51
  • The ```dos2unix``` tool works awesome! Immediately got rid of the error. – pr94 Jul 21 '20 at 07:55