Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

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\""
    
share|improve this answer
add comment

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.