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:


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

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?


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


    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

    echo "export mySite=\"superUser\""
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.