0

Team, am trying to print all elements for array with some string in bash over for loop but its just print elements not the string along.


if [ "$FILTER" = "ALL" ]; then
  vm_ip_all=$(./command_to_get_ips)
  printf "got all IPs \\n %s" "$vm_ip_all"
else
  echo "could not get all IPs"
fi

#for vm_ip in "${vm_ip_all[@]}"; do <<same result as below
for vm_ip in "${vm_ip_all}"; do
  printf "\\n BEGIN FOR \\n"
  echo "iterating for $vm_ip"
echo "END FOR"
done

Actual output:

got all IPs
 10.0.1.6
10.0.1.10
BEGIN FOR
iterating for 10.0.1.6
10.0.1.10

Expected output:

got all IPs
 10.0.1.6
10.0.1.10
BEGIN FOR
iterating for 10.0.1.6
iterating for 10.0.1.10
END FOR

vm_ip_all

10.0.1.6 10.0.1.10 ```
  • 3
    You are populating your `vm_ip_all` array wrong. See methods explained here: https://stackoverflow.com/questions/30988586 – Léa Gris Jul 03 '19 at 18:45
  • hmm still can't figure out. I am getting all elements of ```vm_ip_all`` but not able to repeat the text `iterating for` –  Jul 03 '19 at 19:16
  • Can you update your question with your new `vm_ip_all` array populating code? – Léa Gris Jul 03 '19 at 19:21
  • okay. i pasted how my vm_ip_all looks –  Jul 03 '19 at 19:41

2 Answers2

1

I resolved it

vm_ip_all=$(./command_to_get_ips)
for vm_ip in $vm_ip_all; do
  echo "iterating for $vm_ip"
done
0

To print an array printf doesn't even need a loop. Try something like:

printf '\n BEGIN FOR \n'
printf 'iterating for %s\n' "${vm_ip_all[@]}"
printf 'END FOR\n'
agc
  • 7,973
  • 2
  • 29
  • 50
  • or, when it is not an array, use `printf "iterating for %s\n" ${vm_ip_all}` to avoid a loop. – Walter A Jul 03 '19 at 21:11
  • 1
    @WalterA, True, but irrelevant because the OP was *"trying to print all elements for array"* and `$vm_ip_all` *is* an array. – agc Jul 04 '19 at 14:22