0

Possible Duplicate:
How can I do command line integer & float calculations, in bash, or any language available?

I would like to simply re-assign a variable (to be specific, increment it by 0.050) in a bash script. In the following script that I wrote, i is an (integer) index, and mytime is a decimal/double/float number. "ps" (picosecond) is the unit of time that I am using in my calculations.

#!/bin/bash
mytime = 0.000
for i in {1..3}
do
echo "$i: $mytime ps"
mytime = mytime + 0.050
done

But, when I run this script using bash test.sh, I get these error messages:

test.sh: line 2: mytime: command not found
1:  ps
test.sh: line 6: mytime: command not found
2:  ps
test.sh: line 6: mytime: command not found
3:  ps
test.sh: line 6: mytime: command not found

Why does it seem to be interpreting mytime as a command or a function, instead of as a variable? Can you please help me to correct this?

  • 2
    It looks like you are lacking a basic understanding of bash grammar. You should go read a quick intro or else you will be frustrated to no end by so many different syntax and logic errors. Your assignment syntax is wrong (no spaces allowed, but you need to understand shell grammar to know why), and bash doesn't do floating point math, nor is that the correct syntax for arithmetic expansion. Teaching bash is beyond the scope of a single answer. Try the Wooledge wiki guide for starters. – jw013 Jun 30 '12 at 17:22
  • Thanks! Thanks for pointing out the Wooledge wiki guide! – Andrew Jun 30 '12 at 17:27
5
for i in $(seq 1 0.05 3); do
  # loop body
  echo i equals $i
done
  • This one gets my own +1. :) – Alexios Jun 30 '12 at 17:36
  • @jw013, what is the reason behind the replacement of the backtics-style-command-substitution with a $() one? – maxschlepzig Jun 30 '12 at 18:11
  • @maxschlepzig It's explained in BashFAQ 82. Basically, $() behaves more intuitively with backslashes and can be nested. – jw013 Jun 30 '12 at 18:57
2

Two problems:

  1. Don't use white space. An assignment is VAR=value, not VAR = value, VAR =value or VAR= value. It has to be one shell white space-delimited token, not two or three).
  2. The shell doesn't do arithmetic like that. For integer math, you can say VAR=$(($VAR+1)), or you can read this excellent question for a gazillion other ways (integer, floating point, infix, postfix, possibly even prefix, arbitrary precision, and the kitchen sink): how can I do command line integer & float calculations, in bash, or any language available?

Not the answer you're looking for? Browse other questions tagged or ask your own question.