This is obviously an SSCCE, so it makes (in itself) no sense. E.g. the variable assignment to Y is not used in this minimal example; I'm just trying to figure out the correct syntax to use for my actual case.

I can do the following directly on the bash shell:

Y=10 echo foo

I can also have the following in a bash file foo.sh:

X="echo foo"

... and then do a:


However, when I have the following in a bash file:

X="Y=10 echo foo"

... then, I get:

$ ./foo.sh 
./foo.sh: line 3: Y=10: command not found

What's the correct syntax to use for the above?


The problem is that the optional parameter assignments are recognized before parameter expansion occurs, so the line


is recognized as a command with no preceding assignments. The first word of the result of expanding it is assumed to be the command name, so the shell tries to run Y=10.

As is usually the case, you should not try to store code in a variable, but rather in a function.

X () {
    Y=10 echo foo

It turned out that what I describe below is just an artifact of the minimal example, which leaves out the part where Y is used.

There is a variable assignment before the command in the line:

Y=10 echo foo

The assignment will set the variable Y to 10 during the execution of echo foo. Because echo foo makes no use of Y, the assignment does not have an effect.

In all variants of this command in the question and the answers, that's the same - the Y=10 has no effect there.

  • that's correct; I've updated the question to make that clear. – Marcus Junius Brutus Sep 9 '14 at 23:22
  • Ok; I added a note, and keep it for now for other readers who get confused or curious about that. Feell free to vote down. – Volker Siegel Sep 9 '14 at 23:43

If you must do this, use env:

$ X='env Y=10 echo foo'

...and to demonstrate $Y...

$ X='env Y=10 env'
$ $X | grep \^Y

...but a function is better.


The way to get a command to be parsed again after parameter expansion occurs is

X="Y=10 echo foo"
eval "$X"

I'm assuming that you have a realistic reason for wanting to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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