Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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:

#!/bin/bash
X="echo foo"
$X

... and then do a:

$./foo.sh
foo

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

#!/bin/bash
X="Y=10 echo foo"
$X

... then, I get:

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

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

share|improve this question

4 Answers 4

up vote 4 down vote accepted

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

$X

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
}
share|improve this answer

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.

share|improve this answer
    
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'
foo

...and to demonstrate $Y...

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

...but a function is better.

share|improve this answer

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.

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.