[英]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. 因此(对我而言)似乎将变量v视为字符串或非整数。 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
(( ))
: bash的特定语法是
(( ))
:
(( v += 1 )) # not POSIX compliant, not portable
Alternately, a POSIX-compliant syntax for a math context is $(( ))
: 或者,数学上下文的POSIX兼容语法为
$(( ))
:
v=$(( v + 1 )) # POSIX-compliant!
...or... ...要么...
: $(( v += 1 )) # POSIX-compliant!
There's also the non-POSIX-compliant let
operation: 还有不符合POSIX的
let
操作:
let v+=1 # not POSIX compliant, not portable, don't do this
...and the similarly non-POSIX-compliant declare -i
: ...以及类似的不符合POSIX的
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. Bash不会那样做。 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
: bash <file> duck duck duck goose
输出bash <file> duck duck duck goose
:
duck
1
duck
2
duck
3
goose
4
just add typeset -iv
to your shell: 只需将
typeset -iv
添加到您的shell中:
example: 例:
typeset -i v
v=12
v+=1
echo $v
gives 给
13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.