The Linux Path Environment Variable

Niraj Menon Mar 24, 2022
  1. Usage of PATH in Linux
  2. Ways to Add to PATH Environment in Linux
The Linux Path Environment Variable

In Linux, the PATH environment variable determines the location of programs. It is a list of file paths to directories where binaries or symlinks are placed. When a program invocation is entered, the current shell will look in PATH for the corresponding binary.

This article will discuss how to edit the PATH environment variable to find programs not in a specific location on the file system, assuming a Bash shell command line.

Usage of PATH in Linux

By default, the shell you use will look at the PATH environment variable to locate commands in the directories specified by PATH.

For example, if you typed in cat, a common Linux utility, the shell will typically look in directories like /usr/bin, /usr/local/bin, /usr/sbin, looking for a program named cat, and execute it.

Ways to Add to PATH Environment in Linux

Sometimes, you may have programs that you have installed in locations on your system that are not typically on the PATH, such as your home folder, in a situation where you do not have root access to install into locations like /usr/bin. You can prepend a path to the PATH environment variable to do this.

Suppose you would like to append the path /home/$USER/local/bin - where $USER is a shell variable containing your username and is predefined every time you start a new shell session - to the environment’s PATH.

In Bash, you can do this with the following:

export PATH=/home/$USER/local/bin:$PATH

The export command ensures that the changed PATH will be exported to any subshells or other child commands invoked within the current shell.

Using export is usually the safest option, unless you only need to change the PATH for the current shell but invoke a child process that uses the old PATH value. Keep in mind that you must only add the directory in which the command is contained, not the actual path to the command itself.

You could also choose to set PATH without exporting first, run the command, and then export the new PATH after the command is complete, as shown:

PATH=/home/$USER/local/bin:$PATH
command-that-uses-old-PATH
export PATH

If you need to use variables such as $USER while running in a script, you should use a string to assign to PATH, as shown:

export PATH="/home/$USER/local/bin:$PATH"

In some situations, you may want to append the new path to PATH instead of prepending it, in cases where the priority of the command location does not matter much, such as when you are adding a new command.

You can append to PATH as follows:

export PATH=$PATH:/path/to/new/program