Bash counter increment not working

Hi all,

I'm using Bash 4.3.8 on an Ubuntu system, and no matter what I try, incrementing a counter won't work. The simplest example would be something like this:

#!/bin/bash
myVar=0
myVar=$((myVar++))
echo myVar

The variable should be 1, but it's always 0. I've tried every increment method I know, including:

myVar=$((myVar++))
myVar=$(($myVar+1))
myVar=`expr myVar + 1`
myVar++

And nothing works. I'm pulling my hair out here, can anyone tell me what I'm missing?

Thanks!
Zel2008

myVar=$((myVar+1))  #note that there is no $ sign in myVar 
myVar=`expr $myVar + 1` #note that there has to be $ sign in myVar 
1 Like

Thanks clx,

That's almost got it -- it seems to work outside of a loop, but not inside a loop. If I have a setup like this:

#!/bin/bash
myVar=0
perl -ne 'print if s|blah||' test.xml | while read line
do
echo $line
myVar=$((myVar+1))
echo $myVar
done
echo $myVar

Why does myVar have the correct value inside the loop, and not outside? The output basically goes:

blah
1
blah
2
blah
3
0

Thanks,
Zel2008

That's the variable scoping. The loop runs in subshell and hence they doesn't return the value back to the parent shell.

You can force everything to be executed in the current shell.

 | {
while read line
do
echo $line
myVar=$((myVar+1))
echo $myVar
done
echo $myVar
}
1 Like

The while loop, in this case runs in another subshell with its own scope of variables, which are created and destroy as the while loop starts and finishes.

Some more explanation

1 Like

Thank you both, I didn't know that bash runs in subshells. I learn something new every day, that's the mark of a good Friday. :slight_smile: Everything's working fine now.

#!/bin/bash
var=0
echo $var
((var++))
echo $var

Whats the matter? :wink: