0

I have something like this:

#!/bin/bash

#numero di nodi cache della edge network
NCACHES=$1

#creo vm manager (dello swarm) e balancer
docker-machine create -d virtualbox manager
docker-machine create -d virtualbox balancer

#creo le restanti NCACHES-1 VM
for i in {0..NCACHES-1}
do 
    echo "Creating VM $i"
    docker-machine create -d virtualbox worker$i
done

docker-machine create -d virtualbox backend

IPManager="$(docker-machine ip manager)"
echo "IP VM swarm manager=$IPManager"

IPBalancer="$(docker-machine ip balancer)"
echo "IP VM balancer=$IPBalancer"

for i in {0..NCACHES-1}}
do
    IPCache$i="$(docker-machine ip worker$i)"
    echo "IP worker$i=IPCache$i"
done

I want that in the last loop, i don't know how to pass i index to the "$(docker-machine ip worker$i)" command, and then set IPCache$i to this returned value. Then i don't know how to echo all these IP addresses.

pier92
  • 397
  • 1
  • 11
  • 26
  • 1
    Why don't you make IPCache an array? Then you can have just one IPCache variable and set `IPCache[$i]` – Charles Duffy May 31 '17 at 13:04
  • You're looking for [variable indirection](http://tldp.org/LDP/abs/html/ivr.html), but I second Charles Duffy's suggestion to use an array instead – Aaron May 31 '17 at 13:04
  • 1
    `for i in {0..NCACHES-1}` will never work! brace expansion will happen _before_ variable expansion – Inian May 31 '17 at 13:05
  • You didn't notice a problem with `for i in {0..NCACHES-1}`? – chepner May 31 '17 at 13:05
  • @Aaron, *grumble* re: suggesting the ABS as a reference -- it's the W3Schools of bash, full of outdated information and bad-practice examples. I'd strongly suggest [the BashFAQ #6 section on indirect assignment](http://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables) instead. – Charles Duffy May 31 '17 at 13:05
  • @CharlesDuffy thanks for the info, I'll take care to avoid linking to this site from now on – Aaron May 31 '17 at 13:08

1 Answers1

1

Use an array.

IPCache=()

for ((i = 0; i < NCACHES; i++))
do
    IPCache+=("$(docker-machine ip worker$i)")
    echo "IP worker$i=${IPCache[i]}"
done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578