Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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)
share|improve this question

2 Answers 2

up vote 2 down vote accepted

Use indirect parameter expansion:

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

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

share|improve this answer
    
Thanks! Solved my problem. And I do have input validation, I just removed it to simplify the question. :) –  yellavon Sep 5 '12 at 17:41
    
More information about indirection that I looked up: wiki.bash-hackers.org/syntax/pe#indirection –  yellavon Sep 5 '12 at 17:49

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.

share|improve this answer
    
Please use @choroba's answer, much more elegant. –  terdon Sep 5 '12 at 14:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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