0

I am trying to collect the data from a string of like "2.0 / 3.0".But when I try the following I get an error.

for i in t01 t02 t03 t04 t05 t06 t07 t08 t09 t10 t11; do
    if [ -e "$i/feedback.txt" ]; then
    
        grade=`tail -1 $i/feedback.txt | tr -d [:blank:]`
        if [[ $grade =~ ^[0-9]+\.?[0-9]*/[0-9]+\.?[0-9]*$ ]]; then
            IFS='/' read -ra grArray <<< "$grade"
          
                       
            score=${grArray[0]}
            max=${grArray[1]}
            total_tmax=$total_tmax+$max
            total_t=$total_t+$score
            echo $i: $score / $max
        else 
            echo $i: 0 / 0

Output

t01: 4 / 4
t02: 2 / 3
t03: 3 / 3
t04: 3 / 3
t02/pp_marks.sh: line 39: 13+3.0: syntax error: invalid arithmetic operator (error token is ".0")

  • 1
    When you `IFS='/' read -ra grArray <<< "$grade"` the elements of `grArray` can contain `'.'` characters which leads to your exact error `"invalid arithmetic operator (error token is ".0")` when you attempt to use that in an arithmetic operation (whatever line: 39 is) – David C. Rankin Aug 24 '20 at 03:26
  • If you are expecting lines like `total_t=$total_t+$score` to perform addition, you will be unpleasantly surprised. Since you have floating point numbers, such as `3.0`, bash couldn't add them anyway: bash only does integer arithmetic. It is not clear what you want your full script to do but `awk` is likely a better tool to chose than bash. – John1024 Aug 24 '20 at 03:57
  • You cannot do floating point arithmetic with `bash` arithmetic operators. – M. Nejat Aydin Aug 24 '20 at 04:13

1 Answers1

0

As per comments, bash does not allow floating point arithmetic, only integer. For simple tasks, you can use the bc tool (for more complex operation, consider using a scripting engine like awk, python or perl). Note that with bc you have to specify the precision.

total_tmax=$(bc <<<"scale=1 ; $total_tmax+$max")
total_t=$(bc <<< "scale=1 ; $total_t+$score")
echo "$i: $score / $max"

See Also: How do I use floating-point division in bash?

dash-o
  • 13,723
  • 1
  • 10
  • 37