How to Use $PATH in Bash: Simple Guide and Examples
In bash,
$PATH is an environment variable that lists directories where the shell looks for executable files. You use it to control which commands run by adding or modifying directories in $PATH. For example, echo $PATH shows current directories, and export PATH=$PATH:/new/dir adds a new directory.Syntax
The $PATH variable contains a colon-separated list of directories. Bash searches these directories in order to find executable commands.
Key parts:
echo $PATH: Displays currentPATH.export PATH=...: Sets or updatesPATH.- Directories are separated by colons
:.
bash
echo $PATH export PATH=$PATH:/new/directory
Output
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Example
This example shows how to add a new directory to your PATH and verify it.
bash
echo "Original PATH: $PATH" export PATH=$PATH:/home/user/mybin echo "Updated PATH: $PATH"
Output
Original PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Updated PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/user/mybin
Common Pitfalls
Common mistakes when using $PATH include:
- Overwriting
PATHwithout including the old value, which removes standard command directories. - Forgetting to export
PATHafter changing it, so changes don't apply to child processes. - Adding directories with spaces or incorrect separators.
bash
PATH=/new/dir # This overwrites PATH and removes default directories # Correct way: export PATH=$PATH:/new/dir
Quick Reference
| Command | Description |
|---|---|
| echo $PATH | Show current PATH directories |
| export PATH=$PATH:/new/dir | Add /new/dir to existing PATH |
| export PATH=/new/dir | Replace PATH (dangerous if old PATH lost) |
| which command | Show full path of a command executable |
Key Takeaways
Always include the old PATH when adding new directories to avoid losing standard commands.
Use colons to separate directories in the PATH variable.
Export PATH after modifying it to apply changes to child processes.
Check your PATH with echo $PATH before and after changes.
Avoid spaces or invalid characters in PATH entries.