0

This one is probably pretty simple. I've got a simple while loop which asks the user to input data

while [ $i -le $numMasterNodes ]; do
    echo "Enter hostname #$i: "
    read masterHost$i
    ((i+=1))
done

I'm trying to get the value of $masterHost$i in my loop, for example

while [ $i -le $numMasterNodes ]; do
    echo "Enter hostname #$i: "
    read masterHost$i
    echo $masterHost$i
    ((i+=1))
done

However, it just returns 1 2 3, etc... How can I get the value of $masterHost$i so I can add it to an array?

Thanks!

cookandy
  • 905
  • 1
  • 8
  • 16
  • if masterhost is ="5" and $i="3"..you want to echo "53"...?.. – repzero Nov 19 '15 at 21:33
  • @chepner The question is quite probably a duplicate of something, but my take on it was that OP wanted/needed an ordinary array and didn't know how to [or didn't feel he could use it in the loop] so he tried to "simulate" it, but didn't really want a dynamic variable since he said his end goal was to the data into an array, as per my answer – Craig Estey Nov 19 '15 at 21:57

1 Answers1

2

You probably would be happier with an array. See http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

Note if you already know about arrays, I'm not sure why you're not just using one directly in your loop.

Here's your example recoded to do that:

#!/bin/bash -

i=1
numMasterNodes=3

declare -a masterHost

while [ $i -le $numMasterNodes ]; do
    echo "Enter hostname #$i: "
    read masterHost[$i]
    echo ECHO ${masterHost[$i]}
    ((i+=1))
done
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • Might want an echo -n on the first one to avoid the line break. – Eduardo Nov 19 '15 at 21:34
  • @Eduardo Seems to work fine without. It's just debug AFAICT – Craig Estey Nov 19 '15 at 21:37
  • Of course it works fine, the -n is just to avoid breaking the line when asking for the password. – Eduardo Nov 19 '15 at 21:56
  • thank you! I thin an array is better, as you mentioned. – cookandy Nov 19 '15 at 22:10
  • @Eduardo Oh, okay, I see. You're talking about the _prompt_ [for hostname]. Yeah, I'd do it that way, too. But, here, I chose to take the minimalist route and just fix the basic problem. For other questions [particularly in C], if OP's code is far enough off the mark, I'll even do a full [gratuitous] style cleanup. Herein, style could also include simplifying repetitive constructs or refactoring. Sometimes, it's _really_ necessary, and usually most OPs really appreciate it. I usually make the decision on a case-by-case basis as to how much extra cleanup to do – Craig Estey Nov 19 '15 at 22:17
  • @cookandy You're welcome! The construct you were using reminded me of when [a _long_ time ago] I tried to do something similar. I was in my first few days of shell programming [csh] and I hadn't yet learned about arrays [IIRC, I knew about csh's `argv` but didn't know I could do `set myary=()`, etc.] – Craig Estey Nov 19 '15 at 22:26