5

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?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Great one @anubhava. I think it would be nice if you could explain why the curl command needs to be inside double quotes.
what I need is to add the output of that curl command to the array, Not the command itself.
@zozo6015: Using $(...) i.e command substitution we are adding output of curl command not the command itself.
Thanks @codeforester. I've added some explanation in my answer.
1

You can use +=

declare -a output
for i in $ip
do
  output+=("$(curl -s $i:9200)")
done

2 Comments

I get -bash: syntax error near unexpected token ('`
Yep. Just tested it out, and apparently you can't have a space before +=. Well, you learn something new every day
1

You can capture the output of any command, including a compound command, by enclosing it in $(). Using that technique, you can capture the output of your for loop in a variable like so:

results=$(
  for i in $ip
  do
    curl -s $i:9200
  done
)

In principle, capturing into an array can be done in similar fashion, but handling element delimiters appropriately could prove difficult.

Comments

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.