From: pg on
I want to assign an environment variable temporarily, execute a
command, and then erase the variable. According to the Bash manual and
the "env" manual, these commands should both print "1":

x=1 echo $x

env x=1 echo $x


However, they both print an empty string. What am I doing wrong? For
reference, the Bash manual says:

"The environment for any simple command or function may be
augmented temporarily by prefixing it with parameter
assignments ..."

I'm using Bash 4.0.33 and Coreutils 7.4.
From: Barry Margolin on
In article
<10219d5b-1514-4887-8965-c2f8d7b5d011(a)d27g2000vbl.googlegroups.com>,
"pg(a)gmail.com" <phil.ganchev(a)gmail.com> wrote:

> I want to assign an environment variable temporarily, execute a
> command, and then erase the variable. According to the Bash manual and
> the "env" manual, these commands should both print "1":


Wasn't this question asked and answered a few days ago?
>
> x=1 echo $x
>
> env x=1 echo $x
>
>
> However, they both print an empty string. What am I doing wrong? For
> reference, the Bash manual says:

The problem is that the shell expands all variables on the command line
before executing anything. Try:

x=1 sh -c 'echo $x'

The single quotes prevent the interactive shell from expanding the
variable. Then a subshell is invoked, and it expands the variable in
the command line it receives.

> "The environment for any simple command or function may be
> augmented temporarily by prefixing it with parameter
> assignments ..."
>
> I'm using Bash 4.0.33 and Coreutils 7.4.

--
Barry Margolin, barmar(a)alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
From: Seebs on
On 2010-04-14, pg(a)gmail.com <phil.ganchev(a)gmail.com> wrote:
> I want to assign an environment variable temporarily, execute a
> command, and then erase the variable. According to the Bash manual and
> the "env" manual, these commands should both print "1":
>
> x=1 echo $x
>
> env x=1 echo $x
>
>
> However, they both print an empty string. What am I doing wrong?

You are misunderstanding.

When echo is running, the *environment variable* x will be set to 1.

But echo doesn't use the environment.

Before the command runs (and before any variables are assigned), the
shell first expands variable references in the command, so it expands
$x into an empty string, then sets x to 1, then executes "echo".

$ x=1 sh -c 'echo $x'
1

Basically, it works as documented, but your test case is wrong. :)

-s
--
Copyright 2010, all wrongs reversed. Peter Seebach / usenet-nospam(a)seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
From: pg on
Thank you both for the explanation. Sorry if it was already explained
a few days ago. I did look at older posts, but I must have missed it.
 | 
Pages: 1
Prev: Moving average
Next: bash built-in regex : oddity