Bash变量串联在循环内失败 [英] Bash variable concatenation fails inside loop

查看:59
本文介绍了Bash变量串联在循环内失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下语句:

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

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

串联应该起作用。为什么不呢?循环中有什么不同?

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

以防万一:


> bash -version

> GNU bash,版本4.2.8(1)-发行版(i686-pc-linux-gnu)

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



更新



设置了-eux的输出:

Update

Output with set -eux:

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


推荐答案

类似于 shellcheck 会指出,您正在修改子外壳中的ac_reg_id。

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

重写它以避免子shell:

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" 

这篇关于Bash变量串联在循环内失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆