Bash variable concatenation fails inside loop
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
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"
链接地址: http://www.djcxy.com/p/29144.html
下一篇: 循环内的Bash变量串联失败