Bash变量连接在循环内失败

Mar*_*oDS 1 string variables bash concatenation

鉴于以下陈述:

ac_reg_ids="-1" #Starting value
(mysql) | while read ac_reg_id; do
    echo "$ac_reg_id" #variable is a result of a mysql query. Echoes a number.
    ac_reg_ids="$ac_reg_ids, $ac_reg_id" #concatenate a comma and $ac_reg_id, fails.
done
echo "ac_reg_ids: $ac_reg_ids" #echoes -1
Run Code Online (Sandbox Code Playgroud)

现在根据这个答案:https://stackoverflow.com/a/4181721/1313143

连接应该有效.但是为什么不呢?循环中有什么不同?

以防万一它可能很重要:

> bash -version
> GNU bash,版本4.2.8(1)-release(i686-pc-linux-gnu)

更新

使用set -eux输出:

+ echo 142
142
+ ac_reg_ids='-1, 142'
+ read ac_reg_id
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 5

就像shellcheck会指出的那样,你正在修改子shell中的ac_reg_ids.

重写它以避免子shell:

ac_reg_ids="-1" #Starting value
while read ac_reg_id; do
    echo "$ac_reg_id" 
    ac_reg_ids="$ac_reg_ids, $ac_reg_id"
done < <( mysql whatever )  # Redirect from process substution, avoiding pipeline
echo "ac_reg_ids: $ac_reg_ids" 
Run Code Online (Sandbox Code Playgroud)