The PATH
shell variable in the Bash shell is a special environment variable that tells your
system where to look for executable programs when you type a command.
Why is it needed?
When you type a command like ls
or python
, the system doesn’t magically know where that
program or script is stored. Instead, it searches through a list of directories (folders) defined
in the PATH
variable to find the executable file.
How does PATH
work?
-
The
PATH
is a list of directories:
ThePATH
variable contains multiple directory paths separated by colons:
. For example:/usr/local/bin:/usr/bin:/bin:/home/user/bin
-
Command Search:
When you type a command, Bash searches through each directory in thePATH
one by one (in order) to see if the command's executable file exists there. -
If Found: It runs the program.
If Not Found: Bash returns a "command not found" error.
Example for Beginners
- Suppose your
PATH
looks like this:/usr/local/bin:/usr/bin:/bin
- You type
python
.- Bash will look for an executable named
python
in:/usr/local/bin
/usr/bin
/bin
- If it finds
python
in/usr/bin
, it stops searching and runs it.
- Bash will look for an executable named
Why is PATH
Useful?
- It allows you to run commands without typing the full path to the executable.
For example, instead of:
You can simply type:/usr/bin/python3
python3
- It lets you add custom directories to prioritize or include your own scripts or programs.
Adding a Directory to PATH
To add a directory (e.g., /home/user/scripts
) to your PATH
:
export PATH=$PATH:/home/user/scripts
Now, any executable in /home/user/scripts
can be run directly by typing its name.
In short, the PATH
variable makes it convenient and efficient to execute programs without
needing to type out their full file locations every time. It's like a "search roadmap"
for your system to find commands.