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?
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.
$(...) i.e command substitution we are adding output of curl command not the command itself.You can use +=
declare -a output
for i in $ip
do
output+=("$(curl -s $i:9200)")
done
-bash: syntax error near unexpected token ('`+=. Well, you learn something new every dayYou 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.