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
8
  • It looks fine to me. Is that the exact code that fails, copy-and-pasted, not typed by hand, nothing added or removed? Commented Feb 27, 2013 at 18:40
  • @JohnKugelman yes, I copied it. Commented Feb 27, 2013 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, Commented Feb 27, 2013 at 18:44
  • Please run set -eux before that piece of code, run it again and paste output here. Commented Feb 27, 2013 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. Commented Feb 27, 2013 at 18:48

1 Answer 1

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" 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Okay I got it now. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.