How to use user input with an existing variable

Posted on

Problem :

I’m trying to write a script where the list choice is configurable with the for loop:

list1="name1 name2"
list2="name3 name4"

echo "which list do you want to use? (list1 or list2)"
read userInput

for item in $userInput
do ....

This isn’t working. I also tried this below, but no luck either.

for item in $($userInput)

Solution :

Use indirect parameter expansion:

for item in ${!userInput} ; do
    ...
done

You should validate $userInput before running the loop, though.

It does work, just don’t use the for item in loop. That works for arrays. What you have read into $userInput is a string. Try something like this:

#!/bin/bash 

list1="name1 name2"
list2="name3 name4"

echo "which list do you want to use? (list1 or list2)"
read userInput

if [ $userInput == "list2" ] ;
then
    something
else
    something else
fi

Obviously, change “something” and “something else” to whatever your script needs to do.

Leave a Reply

Your email address will not be published. Required fields are marked *