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 having troubles with a for loop, similar to below:

for VARIABLE in alpha bravo charlie; do
  $VARIABLE=`sed -n '/$VARIABLE/s///gp;' $FILE`
done

$FILE might contain something like

alpha sandy
bravo cathy
charlie barbara

Expected results should be...

echo $alpha     # sandy
echo $bravo     # cathy
echo $charlie   # barbara

Unfortunately I get errors:

bash: alpha=alpha: command not found
bash: bravo=alpha: command not found
bash: charlie=alpha: command not found
share|improve this question

2 Answers 2

up vote 1 down vote accepted

You don't realize it, but you need to run the inner loop twice every time through the loop. Once to get the variable name to assign to, then the second time to actually make the assignment. You do this with eval. I'm too impatient to debug this now, but this should be a start:

for VARIABLE in alpha bravo charlie; do
  eval $VARIABLE=$(sed -n '/$VARIABLE/s///gp;' $FILE)
done

In the general case, you may need to escape $s in your line, depending on whether you want variables substituted in the first run or second. In your case, it doesn't make a difference except for the first one, and you want it on the first invocation.

share|improve this answer
    
eval did it thanks –  Felipe Alvarez Feb 10 '12 at 5:15
    
What did you mean by need to escape $s in your line? –  Felipe Alvarez Feb 10 '12 at 5:16

So you don't have to know the variable names beforehand, you could write:

output=$(sed 's/ \+/="/;s/$/"/' "$FILE")
eval "$output"

echo $alpha     # sandy
echo $bravo     # cathy
echo $charlie   # barbara
share|improve this answer

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.