-1

I want to run a for loop for all strings in a variable (one by one). When I echo my variable it is like this

A=(curl -s 'localhost:9200/something)
echo "$A"

emits:

sss
ddd
fff
ggg
hhh

My for loop is like this:

for i in "${A[@]}"; do
  echo "$i"
  echo test
 done

But loop just run one time and print all data, instead of putting test after each item:

sss
ddd
fff
ggg
hhh
test
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
hamid bayat
  • 2,029
  • 11
  • 20
  • Try simple *echo $A | while read line; do echo $line; done*. – 0andriy Jul 28 '18 at 06:31
  • @0andriy thanks. it work like this: echo "$A" | while read line; do echo "$line"; done – hamid bayat Jul 28 '18 at 06:47
  • `for i in $a; do echo "$i"; echo "test"; done` – Cyrus Jul 28 '18 at 07:03
  • 4
    Better store them in an **actual** array: `a=("sss" "ddd"); for i in "${a[@]}"; do echo "$i"; done` – PesaThe Jul 28 '18 at 08:12
  • 1
    @PesaThe I am running a command and the sending the output to A variable. A=(curl -s 'localhost:9200/something) . the output of this command print strings line by line. how I can send the output to array? – hamid bayat Jul 28 '18 at 08:22
  • @hamidbayat In that case, use the `while read` solution. I wouldn't recommend @Cyrus' solution unless you turn off globbing with `set -f`. – PesaThe Jul 28 '18 at 08:52
  • @hamidbayat, how you're populating that variable is critical -- it's not actually an array when you assign it that way. The question is incomplete without that included inside it. – Charles Duffy Jul 28 '18 at 15:48

1 Answers1

1

As suggested by @PresaThe,

while read line ; do  echo "$line" ; echo testsss; done <  <(curl -s 'localhost:9200/something)
CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section "Answer Well-Asked Questions", and within that the bullet point regarding questions which "*have already been asked and answered many times before*". – Charles Duffy Jul 28 '18 at 15:46