Learn what the PATH environment variable is and how it helps the shell find commands.
When a command like ls or python is executed, a shell needs to know where to find the corresponding executable file.
To do this, shells use the PATH environment variable.
In this concept, we'll learn what the PATH variable is, how a shell uses it to find commands, and how to view and modify it.
When a command like ls or python is executed, a shell needs to know where to find the corresponding executable file.
To do this, shells use the PATH environment variable.
In this concept, we'll learn what the PATH variable is, how a shell uses it to find commands, and how to view and modify it.
PATH is an environment variable that contains a list of directories to search for executable programs.
When a user enters a command that is not a builtin, a shell searches the directories in PATH for an executable file with that name.
The directories in the current PATH can be viewed by printing the PATH variable:
# Switch to Bash if needed
$ bash
# Print the PATH variable
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
Notice that the paths are separated by colons (:). Each path is a directory where a shell will search for executable files.
A shell searches through directories in PATH from left to right:
Since the shell stops at the first match it finds, the order of the directories is important. For example, if a system has two versions of python in different folders, a shell will use the one that comes first in the PATH.
If a shell searches every directory in the PATH and still can't find the executable, it displays a specific error:
$ myprogram
bash: myprogram: command not found
This usually means the program isn't installed or is in a directory not included in the PATH variable.
New directories can be added to PATH so a shell can find programs installed in custom locations:
$ export PATH=$PATH:/home/user/my-tools
In this example, $PATH keeps all the previous directories, and :/home/user/my-tools adds the new directory to the end of the list.
You've now learned about the PATH variable and how a shell locates executable programs.
A quick recap of what we've covered:
For more details on PATH and other environment variables, check out the Bash manual.