How to set environment (PATH) variable permanently in Linux

There is a time when every Linux Administrator gets stuck at a point of his career when he/she has to set a custom path or any other environment variable permanently in the Linux machine.

Suppose you have added a new path to the PATH variable using the shell but you might observe that every time you switch terminal the PATH variable does not works.

 

Solution

To make this issue to be resolved permanently you need to add the variable inside .bashrc or .bash_profile file inside the home folder of the user.

For example, you want to add a PATH variable for root user so you need to add the path inside ~/.bashrc or ~/.bash_profile

Now the confusion comes which file should we place the variable or inside both the files?

 

Difference between .bashrc and .bash_profile

Every time you login to a Linux (Red Hat) machine .bash_profile file is executed

but

In case you are already logged in and you open a new terminal then .bashrc file is executed

So, basically you can put the environment variable inside any of the two files. As per me I would advice you to put the same inside .bash_profile.

WHY?

Have a look at .bash_profile file

# less ~/.bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export PATH=$PATH:/usr/local/samba/bin
You can see in the highlighted part in blue in the above part, every time .bash_profile is executed it also runs .bashrc along with it. As you can see I have added an extra PATH variable for my samba so that I do not need to set it every time I log in.

Sorry for the long post but just thought to clarify in the best possible way from my side.

5 thoughts on “How to set environment (PATH) variable permanently in Linux”

Leave a Comment