In linux, how can we change bash environment variables using initialize script?

0

We know that we can change bash's environment variables, for example PATH, using initialize script, for example .bashrc. Just writing PATH=<VALUE> and you will get what you want.

But, consider this problem:

We have a bash script named rc:

#!/bin/bash  

mySite="superUser"
export mySite
echo "the value of mySite is: $mySite"

Then we declare the variable mySite, execute the rc script, and then check the the variable's value:

$ declare -x mySite="super"
$ ./rc 
the value of mySite is: superUser
$ echo $mySite
super

The value is still super. can we conclude that child shell cannot change parent shell's variable directly using the instruction like VARIALBENAME=VLAUE?

Our rc script is just like .bashrc, and how can we change the bash's environment variable's value by placing the PATH=<VLAUE> in it, for when .bashrc's execution is over, the variable of the calling shell is still not changed?

Yishu Fang

Posted 2012-10-28T08:44:36.830

Reputation: 261

Answers

3

Environment variables are inherited ... and parent processes don't inherit anything from their children (it works in the other direction).

In your first case, the bash process reading the rc file is either the same process in which you use the variable, or its ancestor.

In your second case, the process reading the file is the child of your shell. There are 3 ways around this:

  1. have your script start a new shell, which inherits the variables. Your original shell will resume (with it's original environment) when you exit
  2. source the rc script rather than executing it:

    . ./rc
    

    or

    source ./rc
    

    instructs your current shell to read the script itself (rather than executing it in a child) and then resume

  3. explicitly evaluate the output (as is usually done with ssh-agent for example)

    eval `./rc`
    

    where rc has changed to

    #!/bin/bash
    echo "export mySite=\"superUser\""
    

Useless

Posted 2012-10-28T08:44:36.830

Reputation: 221