0
0
Bash-scriptingHow-ToBeginner · 3 min read

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 current PATH.
  • export PATH=...: Sets or updates PATH.
  • 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 PATH without including the old value, which removes standard command directories.
  • Forgetting to export PATH after 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

CommandDescription
echo $PATHShow current PATH directories
export PATH=$PATH:/new/dirAdd /new/dir to existing PATH
export PATH=/new/dirReplace PATH (dangerous if old PATH lost)
which commandShow 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.