Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store output of for loop into an array or variable

I have a for loop as shown below. I need the whole output of the loop added into an array or variable.

for i in $ip
do
  curl -s $i:9200
done

Any idea how I can achieve that?

like image 707
zozo6015 Avatar asked Jan 25 '17 19:01

zozo6015


People also ask

How do you store results in an array?

All arrays are the contiguous block of memory locations. By default, the lowest position of the array stores the first element, and the highest position stored the last data. In C, the array is declared by specifying the element's type and the total length of array required to store the data.

Can we use for loop in array?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.


1 Answers

You can use it like this:

# declare an array
declare -a arr=()

for i in $ip
do
  # append each curl output into our array
  arr+=( "$(curl -s $i:9200)" )
done

# check array content
declare -p arr

It is important to use quotes around curl comment to avoid splitting words of curl command's output into multiple array entries. With quotes all of the curl output will become a single entry in the array.

like image 198
anubhava Avatar answered Sep 29 '22 12:09

anubhava