简体   繁体   中英

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,

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

Bash doesn't do that. You have to use the mathematical operation syntax $((...)) , viz:

v=0
for var in "$@";do
    echo $var
    v=$((v+1))
    echo $v
one

Output of bash <file> duck duck duck goose :

duck
1
duck
2
duck
3
goose
4

just add typeset -iv to your shell:

example:

typeset -i v
v=12
v+=1
echo $v

gives

13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM