LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   environmental variable in bash command string (http://www.linuxquestions.org/questions/linux-newbie-8/environmental-variable-in-bash-command-string-861648/)

cytmtn 02-09-2011 12:50 PM

environmental variable in bash command string
 
Say I do this:

Code:

a@b:~$ export A=hi
a@b:~$ echo $A
hi
a@b:~$ bash -c "export A=blah; echo $A"
hi
a@b:~$

Why doesn't the bash command print the new value of $A? Is there a way to make it do so?

catkin 02-09-2011 01:17 PM

Quote:

Originally Posted by cytmtn (Post 4253269)
Why doesn't the bash command print the new value of $A? Is there a way to make it do so?

Because bash -c "export A=blah; echo $A" runs export A=blah; echo $A in a sub-process which does not change anything in the parent process.

SaintDanBert 02-09-2011 01:31 PM

If this answers your question, please mark the thread SOLVED.

There are hoops to jump and mountains to climb if you need a child-process to alter
the environment of a parent-process. It is possible but not easy nor recommended.

~~~ 0;-Dan

Kenhelm 02-09-2011 02:15 PM

Use single quotes instead of double quotes.
$A in double quotes gets expanded to 'hi' before the bash -c command is executed
Code:

bash -c 'export A=blah; echo $A'
blah


cytmtn 02-09-2011 02:56 PM

Thanks Kenhelm,

That did the trick.

SaintDanBert 02-09-2011 04:14 PM

Quote:

Originally Posted by Kenhelm (Post 4253344)
Use single quotes instead of double quotes.
$A in double quotes gets expanded to 'hi' before the bash -c command is executed
Code:

bash -c 'export A=blah; echo $A'
blah


(blush) I didn't notice that and should have.
Thanks for the clarification.

~~~ 0;-Dan

SaintDanBert 02-09-2011 04:18 PM

Oh! And you can do this:
Code:

prompt$ $ bash -xc "export A=junk; echo $A"

+ export A=junk
+ A=junk
+ echo stuff
stuff

compared with
Code:

prompt$ $ bash -xc 'export A=junk; echo $A'

+ export A=junk
+ A=junk
+ echo junk
junk

The -x option to bash traces each command as it runs.

Cheers,
~~~ 0;-Dan


All times are GMT -5. The time now is 06:09 PM.