What is the best way to set an environment variable in .bashrc?

17,554

Solution 1

The best way

export VAR=value

The difference

Doing

VAR=value

only sets the variable for the duration of the script (.bashrc in this case). Child processes (if any) of the script won't have VAR defined, and once the script exits VAR is gone.

export VAR=value

explicitly adds VAR to the list of variables that are passed to child processes. Want to try it? Open a shell, do

PS1="foo > "
bash --norc

The new shell gets the default prompt. If instead you do something like

export PS1="foo > "
bash --norc

the new shell gets the prompt you just set.

Update: as Ian Kelling notes below variables set in .bashrc persist in the shell that sourced .bashrc. More generally whenever the shell sources a script (using the source scriptname command) variables set in the script persist for the life of the shell.

Solution 2

Both seem to work just fine, but using export will ensure the variable is available to subshells and other programs. To test this out try this.

Add these two lines to your .bashrc file

TESTVAR="no export"
export MYTESTVAR="with export"

Then open a new shell.

Running echo $TESTVAR and echo $MYTESTVAR will show the contents of each variable. Now inside that same shell remove those two lines from your .bashrc file and run bash to start a subshell.

Running echo $TESTVAR will have an empty output, but running echo $MYTESTVAR will display "with export"

Share:
17,554

Related videos on Youtube

Flávio Amieiro
Author by

Flávio Amieiro

Updated on September 17, 2022

Comments

  • Flávio Amieiro
    Flávio Amieiro about 1 year

    When setting up a variable in .bashrc, should I use this?

    export VAR=value
    

    Or would this be enough?

    VAR=value
    

    What is exactly the difference (if there is one)?

  • krx
    krx over 14 years
    "only sets the variable for the duration of the script (.bashrc in this case)" That is false/misleading. Variables set in this way persist into the interactive shell that read .bashrc.
  • Anthony Geoghegan
    Anthony Geoghegan about 8 years
    PS1 is a bad example of a variable to be exported as an environment variable. It's only meaningful to child processes that are shells and it's interpreted differently by different shells (e.g., bash and dash). Best practice is to simply set it as a regular shell variable in the .bashrc. Better examples of environment variables include HOME, PATH, EDITOR, etc.