Using Export in .bashrc – How to Set Environment Variables in Bash

bashbashrcenvironment-variables

I have noticed in my .bashrc that some lines have export in front of them, such as

export HISTTIMEFORMAT="%b-%d  %H:%M  "
...
export MYSQL_HISTFILE="/root/.mysql_history"

whereas others don't, such as

HISTSIZE=100000

I am wondering if, first, this is correct, and second what the rule is for using export in .bashrc.

Best Answer

You only need export for variables that should be "seen" by other programs which you launch in the shell, while the ones that are only used inside the shell itself don't need to be exported.

This is what the man page says:

The  supplied  names are marked for automatic export to the environā€
ment of subsequently executed commands.  If the -f option is  given,
the  names  refer to functions.  If no names are given, or if the -p
option is supplied, a list of all names that are  exported  in  this
shell  is  printed.   The -n option causes the export property to be
removed from each name.  If a variable name is  followed  by  =word,
the  value  of  the variable is set to word.  export returns an exit
status of 0 unless an invalid option  is  encountered,  one  of  the
names  is  not a valid shell variable name, or -f is supplied with a
name that is not a function.

This can be demonstrated with the following:

$ MYVAR="value"
$ echo ${MYVAR}
value
$ echo 'echo ${MYVAR}' > echo.sh
$ chmod +x echo.sh
$ ./echo.sh

$ export MYVAR="value-exported"
$ ./echo.sh
value-exported

Explanation:

  • I first set ${MYVAR} to be a Shell variable with MYVAR="value". Using echo I can echo the value of it because echo is part of the shell.
  • Then I create echo.sh. That's a little script that basically does the same, it just echoes ${MYVAR}, but the difference is that it will run in a different process because it's a separate script.
  • When calling echo.sh it outputs nothing, because the new process does not inherit ${MYVAR}
  • Then I export ${MYVAR} into my environment with the export keyword
  • When I now run the same echo.sh again, it echoes the content of ${MYVAR} because it gets it from the environment

So to answer your question:

It depends where a variable is going to be used, whether you have to export it or not.

Related Question