Agnus Dei (jackal) wrote in linux,
Agnus Dei

Linux Challenge Question of the Day

Very often I'll set a environment variable before running a command.

For example,
$ sudo JAVA_HOME=/usr/java/default /usr/local/activemq/default/bin/activemq-admin query -QQueue="my.activemq.queue.whatever"

But I've noticed that if I set a variable and then call echo to show that variable echo returns nothing.
$ FOO=bar echo $FOO

(nothing was returned)

But I can export the variable and then call echo and it works:
$ export FOO=bar ; echo $FOO

Or if I set the varaible and then call "env" to check it I see the environment variable is set:
$ LALA=FUN env |grep LALA

So why can't I set the variable and then check it with echo like in the first example above?


I got my answer on facebook from Douglas Kilpatrick who wrote: because variable substitution is done before command parsing. So when the command gets run, it's already "FOO=bar echo ''"

Solution (provided by Douglas Kilpatrick):
$ FOO=baz eval 'echo $FOO'
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

Ohhh...I get it!

At first I didn't understand the answer, but then I looked closer and saw what you typed "FOO=bar echo ''. So in essence, you assigned "bar echo" to the variable FOO in your first command.

If you would have typed:
$Foo=bar | echo $FOO

It should work!...
You missed the point. I can assign an environment variable BEFORE running a command.

The "LALA=FUN env" shows this.

And no I was not assigning "FOO=bar echo" that's not how it works.
Do you always get snarky when someone responds to your posts?
Because that's how your above response comes across...
That statement is meaningless:

FOO=bar echo $FOO

and it does indeed return nothing. FOO is assigned nothing since BASH won't recognize a string with spaces as being a string without quoting it.

However, this works:

FOO=bar; echo $FOO

The semi breaks the one line into two separate commands: the variable assignment, followed by an echo.