0

Possible Duplicate:
How can I add numbers in a bash script

I have a variable that changes value in a for loop:

for i in {1..10..1}
  do
    while ((count < max+1))
      do 
        echo $count >> /directory/outfile_${max}.txt
        ((count++))
      done
    max=$max+100
  done

The ten outfiles should have the names "outfile_100.txt", "outfile_200.txt" etc..

But what happens is that they become like "outfile_100+100+100....txt"

Is it in how I resize max?

Community
  • 1
  • 1
AWE
  • 4,045
  • 9
  • 33
  • 42

4 Answers4

3

max=$max+100 is a string operation. You're saying, "substitute the string represented by the variable $max, then take that string, and the string "+100", and assign it to the variable max." For example, you could say:

max=IamSoSexy+100

because the shell has no types whatsoever, only strings. What you're looking for is a command that interprets its arguments as numbers. You want:

let max=$max+100

because the "let" command does the lifting.

2

You try to compute arithmetic expression and this will not happen with simple assignement. Use max=$(($max + 100))

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

Or use expr

max=`expr $max + 100`
Fernando Miguélez
  • 11,196
  • 6
  • 36
  • 54
  • 1
    While it "works", `expr` is a program used in ancient shell code to do math. In Posix shells like bash, use $(( expression )). In bash and ksh93, you can also use '(( expression ))' or 'let expression' if you don't need to use the result in an expansion. – Gilles Quénot Oct 11 '12 at 15:16
1

You can also set the integer attribute on max, so that arithmetic evaluation is performed on it automatically.

declare -i max
for i in {1..10..1}
do
    while ((count < max+1))
    do 
        echo $count >> /directory/outfile_${max}.txt
        ((count++))
    done
    max+=100
done
chepner
  • 497,756
  • 71
  • 530
  • 681