SyntaxStudy
Sign Up
Linux / Bash Beginner 1 min read

The PATH Variable and source

The `PATH` environment variable is a colon-separated list of directory paths that the shell searches when you type a command without a full path. When you run `python3`, the shell looks through each directory in `PATH` in order and runs the first `python3` executable it finds. This is why installing a tool to a non-standard location requires adding that location to `PATH`. Adding to `PATH` is done by reassigning it: `export PATH="$PATH:/new/directory"`. The new directory can be prepended (higher priority) or appended (lower priority). To make the change permanent, add the export statement to `~/.bashrc` (for Bash interactive shells) or `~/.profile` (for login shells). Changes to `~/.bashrc` take effect in new terminal sessions or after running `source ~/.bashrc`. The `source` command (or its alias `.`) executes a script in the current shell context rather than in a child process. This means variable assignments and function definitions in the sourced file persist in the current session. This is how shell startup files work and how dotenv files are loaded. The `which`, `type`, and `command -v` utilities help you locate executables and understand how commands are resolved.
Example
# Display current PATH
echo $PATH
# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Find where a command lives
which python3
# /usr/bin/python3

which -a python3        # Show all matches in PATH
type python3            # Also shows aliases, builtins
command -v git          # Portable way to check if command exists

# Add a directory to PATH (current session only)
export PATH="$PATH:/opt/myapp/bin"

# Prepend (higher priority)
export PATH="/opt/myapp/bin:$PATH"

# Add to PATH permanently (append to ~/.bashrc)
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

# Reload ~/.bashrc in current session
source ~/.bashrc
# Equivalent shorthand
. ~/.bashrc

# Create a local bin directory and add to PATH
mkdir -p ~/.local/bin
export PATH="$HOME/.local/bin:$PATH"

# Install a script to local bin
cp myscript.sh ~/.local/bin/myscript
chmod +x ~/.bashrc/myscript

# Source a .env file
# cat .env:
# export DB_HOST=localhost
# export DB_PASS=secret

source .env
echo $DB_HOST      # localhost

# Inspect all shell startup file locations
# /etc/profile          login, all users
# /etc/bash.bashrc      interactive, all users
# ~/.bash_profile       login, current user
# ~/.bashrc             interactive, current user
# ~/.bash_logout        on logout