Why doesn't this bash expr command work?

Marin picture Marin · Jan 24, 2011 · Viewed 44.3k times · Source

I am trying to increment a variable in a bash script and it is not working. Here is my code:

#! /bin/bash

COUNTER=0
while [ $COUNTER -lt 5 ]
do
    echo "i will add this line to file mycreation">>./myfile
    COUNTER = `expr $COUNTER + 1`
done

The quotes around the COUNTER assignment are backticks.

I tried replacing COUNTER with $COUNTER like this:

$COUNTER = `expr $COUNTER + 1`

But that did not solve the problem and gave me the following error:

line7: 0: command not found. 

Answer

Shawn Chin picture Shawn Chin · Jan 24, 2011

As @Cory rightly pointed out, there should not be spaces around the equal sign or else bash will confuse COUNTER for a command.

COUNTER=$(expr $COUNTER + 1)

going off-topic ...

That said, you could avoid having bash fork a subprocess by using the following alternatives:

In fact, your while loop can be written as:

for ((COUNTER=0; COUNTER <= 5 ; COUNTER++))
do
    echo "i will add this line to file mycreation">>./myfile
done

Breaking down the error message

When you were met with the error:

line 7:   0:    command not found.
'-----'  '--'  '------------------'
   |       |                 |
location   |            Description of error.
          culprit 

my guess is what you had on line 7 was

$COUNTER = `expr $COUNTER + 1`
--------   --------------------
    |                 |
Evaluated to 0        |
                  Evaluated to 1

What bash ends up see is 0 = 1 and since bash statements are generally in the form command arg1 arg1 ..., bash interprets it as run the command 0 with arguments = 1. Thus the error message : 0: command not found.

When you removed the spaces around the equal sign, what bash ends up interpreting is:

0=1

which means run command 0=1 with no arguments, hence the error 0=1: command not found.

Variable assignments should be in the form VAR_NAME=VALUE (without the $), so the syntax you should be using is:

COUNTER=`expr $COUNTER + 1` # or any of the variants above

which bash evaluates and eventually interpret as:

COUNTER=2