Problem running var (with spaces) as command

I seem to be fighting bash's shell expansions..

I set this variable:
CMD="export MVAR=\"1 2 3\""

if I try to run it, it is clear the shell is parsing along the spaces of the contents of MYVAR:

> $CMD
+ export 'MYVAR="1' 2 '3"'
+ MYVAR='"1'
-bash: export: `2': not a valid identifier
-bash: export: `3"': not a valid identifier

Is there any set of escapes / quoting that will get bash to keep the MYVAR contents together when I run it? I'd prefer not to use eval, since I'm passing my CMD to a function in another script I don't control.

Thanks!

Use 'eval'

CMD="export MVAR='1 2 3'"

eval $CMD

echo $MVAR
1 2 3

No. If you double quote CMD then it will expand to one token and the shell will start looking for a command to execute whose name is the entire string, spaces and all. So, you cannot double quote $CMD when you invoke it. Without the double quotes, the results of the expansion will undergo field splitting, and quotes within the expansion are not special so they cannot be used to affect the field splitting step.

(Assuming a typical posix-like shell) Your only option is eval. Without it, what you are trying to do is impossible.

CMD='eval export MVAR="1 2 3"'

Regards,
Alister

Alister, thanks for the definitive answer.