Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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!

like image 477
Zivxx Avatar asked Mar 18 '14 13:03

Zivxx


People also ask

What are arithmetic operators?

An operator that performs arithmetic operations on groups and numbers. In AHDL, supported arithmetic operators in Boolean expressions consist of the prefix and binary plus ( + ) and minus ( - ) symbols.

How do you float a division in bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part. Rounding as needed.


1 Answers

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")
like image 155
devnull Avatar answered Nov 10 '22 00:11

devnull