Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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`

$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
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)

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .