Linux: How to add a directory in PATH permanently

PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for…

Linux: How to add a directory in PATH permanently
Photo by Gabriel Heinzer on Unsplash

PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for executable files (i.e., ready-to-run programs) in response to commands issued by a user. It increases both the convenience and the safety of such operating systems and is widely considered to be the single most important environmental variable.

There are two ways of adding a directory to PATH, the first way is for each individual user and the seconds one is the global one which affects all users.

Example: How to add a directory to the PATH of all users.

Assume that we want to add directory /tools/ to the PATH of all users, open as root or with sudo file /etc/profile and add to the end of the file the following line.

export PATH="/tools/:$PATH"

For changes to take effect the user must login again or enter

source /etc/profile

Example: How to add a directory to the PATH of a user.

Assume that for user kpatronas we want to add directory /scripts to his PATH, to do this open /home/kpatronas/.bashrc and add to the end of the file the following

export PATH="/scripts/:$PATH"

For changes to take effect user kpatronas must log out and login again or enter

source ~/.bashrc

Example: How to remove a directory for the PATH

Removing an entry from PATH is a bit tricky! you need first to remove the entry from /etc/profile or .bashrc and then remove the entry from the PATH variable through bash in order to avoid logout.

Then to remove /scripts/ from the user session enter:

export PATH=`echo $PATH | tr -s ":" "\n"  | grep -v '/scripts/' | tr -s "\n" ":"`

This command pipes echo to the tr command which replaces : with a new-line, then filters out the directory we want to remove from PATH and then replace the new-line with the : again and finally re-assign the value to the PATH variable.

Conclusion

Learning how to change the value of PATH globally or for an individual user is a must for any DevOps, Developer or System Administrator! I hope this article was easy to understand and helped you!