Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this bash expr command work? [duplicate]

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. 
like image 595
Marin Avatar asked Jan 24 '11 17:01

Marin


2 Answers

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:

  • Using the bash builtin 'let' command:

    let COUNTER="COUNTER + 1"
    
  • or, using bash c-style expression:

    (( COUNTER++ ))
    

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
like image 195
Shawn Chin Avatar answered Sep 28 '22 00:09

Shawn Chin


Remove the spaces around the equals sign:

COUNTER=`expr $COUNTER + 1`
like image 38
Cory Klein Avatar answered Sep 28 '22 02:09

Cory Klein