0

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

1
  • 2
    Sounds like a job for an array (see BashFAQ #5). Use e.g. read var[0] to fill values, and "${var[0]}" to access it. Commented Apr 12, 2021 at 5:45

2 Answers 2

1

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[@]}.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.