1

I'm having trouble getting the value of a variable into an array in Bash (I'm using bash v3.2.25).

I have some output from a command, piped into:

while read domain; do domains=("${domains[@]}" "domain"); done

But then echo ${#domains[@]} returns 0.

I've also tried various forms of:

while read domain; do domains+=($domain); done

with all sorts of attempts at quoting and double quoting, but no matter what, the domains array stays empty.

What am I doing wrong?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
JediWombat
  • 36
  • 4
  • You shouldn't have the second `domain` in quotes, should you? – NetMage May 19 '17 at 23:44
  • 1
    Specifically, either `domains=("${domains[@]}" "$domain")` (with `$`) or `domains+=("$domain")` should work, but the changes get lost when your `while` loop ends. [This answer](http://stackoverflow.com/questions/16854280/a-variable-modified-inside-a-while-loop-is-not-remembered) talks about getting around that problem. – cxw May 19 '17 at 23:46
  • In what context is this code called? Almost certainly it's in a pipeline -- you need to **show** us that pipeline. See [BashFAQ #24](http://mywiki.wooledge.org/BashFAQ/024). – Charles Duffy May 19 '17 at 23:59
  • Thanks guys. Yes, it was in a pipeline. I didn't find the answers when searching because I didn't realise the while loop was the problem - I was looking for array help. The question that this has been linked to has given me the answers I needed :) – JediWombat May 22 '17 at 01:40

0 Answers0