1

so I've this shell script, where i take simple user input of IPs and store that into a text file.

MasterNode(){
echo "Enter number of Master Node below"
read -r numESM

for ((i=1; i<=${numESM}; i++))
  do
    echo "${bold}Enter Master node server IP below${normal}"
    read IPS;
    echo "${IPS}" >> /path/Master.txt 2>&1
done
}
MasterNode

Master.txt output is this

1.1.1.1
2.2.2.1
1.1.2.1

and i want to save these IPs in this format into another file (configuration) file

discovery.seed_hosts: ["1.1.1.1", "2.2.2.1","1.1.2.1"]
cluster.initial_master_nodes: ["1.1.1.1","2.2.2.1"]

Is there any way by which I can store each value which I get in the loop into some dynamic variable like, when the loop runs first the value is stored in A[0] and A[0] have value 1.1.1.1 similarly A[1] which have value 2.2.2.1. then getting its value just like any other vairable in bash.

0

How about this:

echo "Enter number of Master Node below"
read -r numESM

IPS=() # make empty array
for ((i=1; i<=${numESM}; i++))
do
    echo "Enter Master node server IP below"
    read IP;
    IPS+=($IP) # add entry to array
done

line="discovery.seed_hosts: ["
for i in "${IPS[@]}"
do
    line="${line}\"${i}\"," # add entry to line
done

line="${line%?}" # remove last ","
line="${line}]"  # add "]"
echo $line

You know how to put that into your function, right? Another way would be to add entries to the line as they are entered and get rid of one for loop. However, you have more possibilities how to add them, and which to add to a line in another for loop. Here is it with one for loop:

echo "Enter number of Master Node below"
read -r numESM

line="discovery.seed_hosts: ["
for ((i=1; i<=${numESM}; i++))
do
    echo "Enter Master node server IP below"
    read IP;
    line="${line}\"${IP}\","
done

line="${line%?}" # remove last ","
line="${line}]"  # add "]"
echo $line

Warning: It does not work properly for 0 entries.

2
  • @noody this is exactly what I was looking for... thank you so much. really appreciate your help – Tim drake Feb 19 at 6:56
  • Make sure you always keep the variables quoted: IPS+=("$IP") -- there's no telling what a user will enter that can trip you up. – glenn jackman Feb 19 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.