Common Environment Variables: HOME, PATH, USER, and PWD

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 39 of 205

Every Bash session starts with a set of ready-made variables. Four of them appear in almost every script: HOME, PATH, USER, and PWD. Knowing what each one holds, who sets it, and when it can be missing lets you write scripts that work on any machine.

The sample outputs in this lesson use a user named ana on a typical Linux system. Your values will differ.

HOME: The Home Directory

HOME holds the path of the current user's home directory, the place where personal files and settings live:

echo "$HOME"
/home/ana

Bash uses HOME in two ways that you meet every day.

The first is the tilde. When a word begins with ~, Bash replaces the tilde with the value of HOME. Changing the variable changes what the tilde means, as this test inside a subshell shows:

( HOME=/tmp/fakehome; echo "tilde: ~ -> $(echo ~)" )
tilde: ~ -> /tmp/fakehome

The second is the cd command. With no argument, cd changes to the directory in HOME:

cd
pwd
/home/ana

A script that needs the user's configuration should build paths from "$HOME", as in "$HOME/.config/myapp", and never write /home/ana directly.

USER: The Name of the Current User

USER holds the login name of the user, such as ana. A closely related variable, LOGNAME, usually holds the same value.

Unlike HOME, USER is not set by Bash itself. A login program or the desktop session sets it, and it can be missing in some places: inside a minimal container, under cron, in a script started with an empty environment, or after env -i. If a script relies on USER, it may break there.

The id -un command asks the system directly and always works. A reliable pattern prefers USER and falls back to id -un:

user_name="${USER:-$(id -un)}"
echo "Running as: $user_name"
Running as: ana

The expansion ${USER:-...} uses USER when it is set and not empty, and runs the id -un command substitution only when it is not. The whoami command gives the same answer as id -un.

PWD: The Current Working Directory

PWD holds the directory you are currently in. Bash updates it every time cd succeeds, and the pwd command prints it:

cd /usr
echo "PWD=$PWD"
PWD=/usr

Bash also keeps the previous directory in OLDPWD. That variable powers the shortcut cd -, which returns to the earlier directory and prints it:

cd /usr
cd /tmp
echo "PWD=$PWD OLDPWD=$OLDPWD"
cd -
PWD=/tmp OLDPWD=/usr
/usr

When you enter a directory through a symbolic link, PWD keeps the path as you typed it, while pwd -P prints the real physical location:

mkdir -p real_dir
ln -sfn real_dir link_dir
cd link_dir
echo "PWD=$PWD"
echo "pwd -P=$(pwd -P)"
PWD=/home/ana/link_dir
pwd -P=/home/ana/real_dir

The first line is the logical path and the second the physical one. Scripts that compare directories should use pwd -P so that two paths to the same place look the same.

Assigning to PWD Does Not Move You

PWD is only a record of where you are. Setting it by hand does not change the real working directory, and the value is corrected the next time cd runs:

PWD=/not/real
pwd
echo "PWD variable now: $PWD"
cd .
echo "after cd: $PWD"
/home/ana
PWD variable now: /not/real
after cd: /home/ana

Always use cd to change directories.

PATH: Where Bash Looks for Commands

PATH is a list of directories, separated by colons. When you type a command name that has no slash in it, Bash searches those directories from left to right and runs the first matching executable file:

echo "$PATH"
/home/ana/.local/bin:/usr/local/bin:/usr/bin:/bin

To read the list more easily, translate the colons into new lines:

tr ':' '\n' <<<"$PATH"
/home/ana/.local/bin
/usr/local/bin
/usr/bin
/bin

The type command shows which file Bash finds for a name. With -a it shows every match, in search order:

type -a ls
ls is /usr/bin/ls
ls is /bin/ls

On modern systems /bin is often a link to /usr/bin, which is why the same program appears twice. Use command -v name to print just the first match or to test whether a command exists:

if command -v git >/dev/null; then
  echo "git found"
else
  echo "git missing"
fi
git found

The First Match Wins

Because the search stops at the first match, the order of the directories matters. Here are two folders that each contain a program called mytool:

mkdir -p first_dir second_dir
printf '#!/usr/bin/env bash\necho "tool from first_dir"\n' > first_dir/mytool
printf '#!/usr/bin/env bash\necho "tool from second_dir"\n' > second_dir/mytool
chmod +x first_dir/mytool second_dir/mytool

PATH="$PWD/first_dir:$PWD/second_dir:$PATH"
mytool
type -a mytool
tool from first_dir
mytool is /home/ana/first_dir/mytool
mytool is /home/ana/second_dir/mytool

Both programs are on the path, but only the one in the earlier directory runs. Reversing the order of the two entries makes the other one run.

Adding Your Own Directory to PATH

A script in your own folder cannot be run by name until its folder is on PATH. This example creates a command and shows the failure before the change and the success after it:

mkdir -p bin_demo
cat > bin_demo/hello_cmd <<'EOF'
#!/usr/bin/env bash
echo "hello from hello_cmd"
EOF
chmod +x bin_demo/hello_cmd

hello_cmd
PATH="$PWD/bin_demo:$PATH"
hello_cmd
command -v hello_cmd
bash: hello_cmd: command not found
hello from hello_cmd
/home/ana/bin_demo/hello_cmd

The assignment puts the new folder in front of the old list, and the $PATH at the end keeps the existing entries. A common mistake is writing PATH="$PWD/bin_demo" alone, which discards the old list, so even ls stops working. Lesson 35 showed that failure.

Put new directories at the end instead (PATH="$PATH:$HOME/bin") when you do not want your files to take priority over the system's programs. Also avoid a leading, trailing, or doubled colon in PATH: Bash reads an empty entry as the current directory, which lets any program in whatever folder you are in run by name and is a security risk.

Splitting PATH in a Script

A script can read PATH into an array by temporarily changing the separator that read uses:

IFS=: read -ra dirs <<<"/usr/local/bin:/usr/bin:/bin"
printf '%s\n' "${dirs[@]}"
/usr/local/bin
/usr/bin
/bin

The IFS=: before read applies only to that command. The -a option stores the pieces in an array called dirs, and printf prints one item per line. A later lesson explains arrays in full.

What Bash Sets When the Environment Is Empty

Bash does not depend entirely on its parent for these variables. Start Bash with an empty environment and look at what it supplies on its own:

env -i /usr/bin/env bash -c 'echo "USER=[${USER-unset}] HOME=[${HOME-unset}] PWD=[$PWD]"; echo "PATH=[$PATH]"'
USER=[unset] HOME=[unset] PWD=[/home/ana]
PATH=[/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

Bash set PWD itself, and it filled in a default PATH, so basic commands still work. It did not invent HOME or USER. A script that must run in such a stripped environment, such as one started by cron or a container, should supply or check these variables itself.

A Few Other Standard Variables

Several more variables show up in scripts and in documentation:

VariableTypical meaning
SHELLThe path of the user's login shell, such as /bin/bash
LANGThe language and character-set settings, such as en_US.UTF-8
EDITORThe text editor that programs open when they need one
TERMThe terminal type, which controls colors and cursor movement
OLDPWDThe previous working directory, used by cd -

Some of these may be unset on a given machine. Use the ${NAME:-default} form whenever a script depends on one.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Common Environment Variables: HOME, PATH, USER, and PWD and get answers drawn from it.

Signed-in readers only.