[英]Variable is concatenating, not incrementing in BASH
這是代碼:
v=0
for var in "$@";do
echo $var
v+=1
echo $v
done
這是命令:
$ bash MyScript.sh duck duck goose
這是輸出:
duck
01
duck
011
goose
0111
因此(對我而言)似乎將變量v視為字符串或非整數。 我不確定為什么會這樣做,我覺得這是一個簡單的問題,我只是忽略了一個小細節。
這是非靜態類型陷阱的一個例子嗎?
謝謝,
使用數學上下文執行數學。 bash的特定語法是(( ))
:
(( v += 1 )) # not POSIX compliant, not portable
或者,數學上下文的POSIX兼容語法為$(( ))
:
v=$(( v + 1 )) # POSIX-compliant!
...要么...
: $(( v += 1 )) # POSIX-compliant!
還有不符合POSIX的let
操作:
let v+=1 # not POSIX compliant, not portable, don't do this
...以及類似的不符合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不會那樣做。 您必須使用數學運算語法$((...))
,即:
v=0
for var in "$@";do
echo $var
v=$((v+1))
echo $v
one
bash <file> duck duck duck goose
輸出bash <file> duck duck duck goose
:
duck
1
duck
2
duck
3
goose
4
只需將typeset -iv
添加到您的shell中:
例:
typeset -i v
v=12
v+=1
echo $v
給
13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.