1

I have loop which writes to file, but I want to write each 0.5 value to the file. I tried with let count+=0.5 but that didn't work somehow. Is this possible?

Script:

#!/bin/bash
COUNTER=50
count=0
until [  $COUNTER -lt 20 ]; do
        echo $count >> value.txt
        echo COUNTER $COUNTER
        let COUNTER-=1
        let count+=0.5
        sleep 1
done

1 Answers1

3

bash doesn't do floating-point arithmetic natively; you need to use an external tool. -= is also not a supported operator.

until [ "$COUNTER" -lt 20 ]; do
    printf "%0.1f\n" "$count"
    echo "COUNTER $COUNTER"
    count=$(bc <<< "$count + 0.5")
    COUNTER=$((COUNTER - 1))
    sleep 1
done > value.txt
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Precisely what I was about to suggest: +1 – dsclose Apr 28 '16 at 16:21
  • I receive this error: `./test.sh: line 7: bc <<< "0 + 0.5": syntax error: operand expected (error token is "< "0 + 0.5"")` –  Apr 28 '16 at 16:24
  • Are you sure you are using `bash`? Try `count=$((echo "$count + 0.5" | bc))` instead. – chepner Apr 28 '16 at 16:27
  • I am using bash, With that I get this error `./test.sh: line 10: echo "0 + 0.5" | bc: syntax error: invalid arithmetic operator (error token is ""0 + 0.5" | bc")` –  Apr 28 '16 at 16:34
  • 1
    Ugh. I can't count. I did some copy/paste in my answer, and forgot to change `$((...))` to `$(...)` for the `bc` command. – chepner Apr 28 '16 at 16:36
  • One question, the first value is `0` the second is `.5` third `1.0`. Why isn't the second `0.5`? –  Apr 28 '16 at 16:40
  • `bc` is more about the calculation than the format. There might be a way to adjust the output for `bc`, but it's easier (given my limited knowledge of `bc`) to accommodate that with `printf`; see my update. – chepner Apr 28 '16 at 16:43