Bash variable concatenation fails inside loop

一笑奈何 提交于 2020-01-05 08:52:53

问题


Given the following statements:

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

Now according to this answer: https://stackoverflow.com/a/4181721/1313143

Concatenation should work. Why doesn't it, though? What's different within the loop?

Just in case it could matter:

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

Update

Output with set -eux:

+ echo 142
142
+ ac_reg_ids='-1, 142'
+ read ac_reg_id

回答1:


Like shellcheck would helpfully have pointed out, you're modifying ac_reg_ids in a subshell.

Rewrite it to avoid the subshell:

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" 


来源:https://stackoverflow.com/questions/15119616/bash-variable-concatenation-fails-inside-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!