Josafoot Josafoot - 4 months ago 11
Bash Question

Variable is concatenating, not incrementing in BASH

Here is the code:

v=0
for var in "$@";do
echo $var
v+=1
echo $v
done


Here is the command:

$ bash MyScript.sh duck duck goose


Here is the output:

duck
01
duck
011
goose
0111


So it appears (to me) to be treating the variable v as a string or not an integer. I am not sure why it would do this and I feel like this is a simple issue that I am just overlooking one small detail.

Is this an example of the pitfalls of non-static typing?

Thanks,

Answer

Use a math context to perform math. The bash-specific syntax for this is (( )):

(( v += 1 )) # not POSIX compliant, not portable

Alternately, a POSIX-compliant syntax for a math context is $(( )):

v=$(( v + 1 )) # POSIX-compliant!

...or...

: $(( v += 1 )) # POSIX-compliant!

There's also the non-POSIX-compliant let operation:

let v+=1 # not POSIX compliant, not portable, don't do this

...and the similarly non-POSIX-compliant declare -i:

declare -i v # not POSIX compliant, not portable, don't do this
             # ...also makes it harder to read or reuse snippets of your code
             # ...by putting action and effect potentially further from each other.
v+=1