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.

1
  • 1
    Variable assignments in POSIX compliant shells don't take $ before the variables names. You should just do a=$(expr "$a" + 1) Commented Jan 21, 2019 at 12:33

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

i made the said corrections but i am getting a new error bash: [: missing ]' `
yes it does, Thank you.
0

You can use one of arithmetic expansion:

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

Read also this guide

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.