Variable is concatenating, not incrementing in BASH -


here code:

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

here command:

$ bash myscript.sh duck duck goose 

here output:

duck 01 duck 011 goose 0111 

so appears (to me) treating variable v string or not integer. not sure why , feel simple issue overlooking 1 small detail.

is example of pitfalls of non-static typing?

thanks,

use math context perform math. bash-specific syntax (( )):

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

alternately, posix-compliant syntax math context $(( )):

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

...or...

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

there's non-posix-compliant let operation:

let v+=1 # not posix compliant, not portable, don't 

...and non-posix-compliant declare -i:

declare -i v # not posix compliant, not portable, don't              # ...also makes harder read or reuse snippets of code              # ...by putting action , effect potentially further each other. v+=1 

Comments