Skip to main content
4 of 4
Restored conversational tone ;-)
le_jawa
  • 113
  • 1
  • 6

Bash interpreting a variable assignment as a command

I've been trying to do something for a couple of days, and I'm stumped; I keep running into the same problem, no matter how I approach this. I have a text file with 2 columns in it; the first is the variable name, the second is the command to be run, with the output being assigned to the variable in the first column. I use read to assign both columns to their own variables, then put the full expression into a new variable and execute it. No matter how I do it, I always get the expression as a command name and the error "command not found."

That's all a little convoluted, so let me show you. The script is:

while read varName varCmd
do
        echo varName is $varName
        echo varCmd is $varCmd
        declare cmd=$varName=$varCmd
        echo Command is $cmd
        "$cmd"
        echo 1st Value is $varFoo
        echo 2nd Value is $varBar

done < testvars.txt

And the text file is:

varFoo  echo foo
varBar  echo bar

Everything works except the assignment execution itself. Here's what I get:

varName is varFoo
varCmd is echo foo
Command is varFoo=echo foo
./testvars.sh: line 8: varFoo=echo foo: command not found
1st Value is
2nd Value is
varName is varBar
varCmd is echo bar
Command is varBar=echo bar
./testvars.sh: line 8: varBar=echo bar: command not found
1st Value is
2nd Value is

It looks like Bash is interpreting the whole thing as one command name (string) and not interpreting the = as an operator.

What can I do to get Bash to correctly interpret the assignment expression correctly?

le_jawa
  • 113
  • 1
  • 6