1

I want to increment a variable whose value is set to 23. After each increment it should print out the new value here is my code.

a=23
while [ $a -lt 45 ];


do  
$a =  `expr $a + 1` ; 
echo " the new value is $a "; 
done

But I am getting a result like this.

enter image description here

Basically it is not incrementing.

Can someone correct the code.

Inian
  • 80,270
  • 14
  • 142
  • 161
Danish Xavier
  • 1,225
  • 1
  • 10
  • 21
  • 1
    Variable assignments in POSIX compliant shells don't take `$` before the variables names. You should just do `a=$(expr "$a" + 1)` – Inian Jan 21 '19 at 12:33

2 Answers2

2

You are using the $sign in a left assignment statement, which is not what you expect. Please change your line

$a =  `expr $a + 1` ; 

to

a=`expr $a + 1`;

And also be warned that spaces before and after = sign shouldn't be used in bash scripts

UPDATE: This code does work without syntax errors with bash or sh:

a=23
while [ $a -lt 45 ]; do  
  a=`expr $a + 1` 
  echo "the new value is $a"
done

And prints:

the new value is 24
the new value is 25
the new value is 26
the new value is 27
the new value is 28
the new value is 29
the new value is 30
the new value is 31
the new value is 32
the new value is 33
the new value is 34
the new value is 35
the new value is 36
the new value is 37
the new value is 38
the new value is 39
the new value is 40
the new value is 41
the new value is 42
the new value is 43
the new value is 44
the new value is 45
MarcoS
  • 17,323
  • 24
  • 96
  • 174
0

You can use one of arithmetic expansion:

a=$((a+1))
((a=a+1))
((a+=1))
((a++))

Read also this guide

Sergey Podgornyy
  • 663
  • 10
  • 19