Reputation: 11
Probably a noob question, but I'm having a particular challenge where I want to dynamically generate variable names based on a value. Eg. If I'd require 3 variables, variable names to be incremented dynamically var_0,var_1,var_3 respectively.
The solution I have right now is barebones. I'm just using read -p
get user input and save it to variable. So for 5 hosts, I've just duplicated this 5 times to get the job done, but not a clean solution. I was looking around and reading through declare
and eval
but haven't got anywhere
Thinking of a solution where I input no. of hosts first and this dynamically picks up and asks for user input based on number of hosts and saves to variables incremented dynamically
Any help is appreciated, cheers
Upvotes: 0
Views: 78
Reputation: 27215
Use arrays. However, you don't have to ask the user for the number of hosts. Let them enter as many hosts as they like and finish by entering an empty line:
echo "Please enter hosts, one per line."
echo "Press enter on an empty line to finish."
hosts=()
while read -p "host ${#hosts[@]}: " host && [ -n "$host" ]; do
hosts+=("$host")
done
echo "Finished"
Alternatively, let the user enter all hosts on the same line separated by whitespace:
read -p "Please enter hosts, separated by whitespace: " -a hosts
To access the individual hosts use ${hosts[0]}
, ${hosts[1]}
, ..., ${hosts[${#hosts[@]}]}
.
To list them all at once use ${hosts[@]}
.
Upvotes: 1
Reputation: 7277
Use an array instead!
But read
can actualy create dynamic vars, just like this:
for i in {1..3}; do
read -p 'helo: ' var_$i
done
Upvotes: 0