1

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
Community
  • 1
  • 1
MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • It looks fine to me. Is that the exact code that fails, copy-and-pasted, not typed by hand, nothing added or removed? – John Kugelman Feb 27 '13 at 18:40
  • @JohnKugelman yes, I copied it. – MarioDS Feb 27 '13 at 18:40
  • what version of bash are you using? I have just tried this using 4.2.24, and the output of your sample code is exactly what you would expect, if `ac_reg_id` variable is not set, last line prints `-1, ` – Alex Feb 27 '13 at 18:44
  • Please run `set -eux` before that piece of code, run it again and paste output here. – emi Feb 27 '13 at 18:46
  • @Alex I added version. It's a bit older than yours but I don't see how it could matter in such small difference. – MarioDS Feb 27 '13 at 18:48
  • @esauvisky I added the results to my answer. – MarioDS Feb 27 '13 at 18:51
  • Where did that `read` come from? You're probably clearing the variable `ac_reg_id`! – emi Feb 27 '13 at 18:54
  • @esauvisky I added more context, however I don't think it could make a difference since the snippet is part of a bigger script where I'm using variables in the same way, just without concatenation, and the rest of it works. Edit: uh-oh. Seems like a didn't get "scope" quite well here. – MarioDS Feb 27 '13 at 18:56

1 Answers1

5

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" 
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • I'll see if it does the trick. Thanks for pointing out that website, didn't know about it yet. Could you give more information about how "< <" works? I'm pretty new with bash. – MarioDS Feb 27 '13 at 19:01
  • There is no `< <`. There is `<` which redirects from a file as I'm sure you already know, and there's `<(cmd)` which expands to a filename which when read produces the output from `cmd`. Any variation on this, such as `<< (cmd)`, `<<(cmd)` or `< < cmd` is invalid. – that other guy Feb 27 '13 at 19:03
  • Okay I got it now. Thank you. – MarioDS Feb 27 '13 at 19:09