Tilde Expansion and Home Directories

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 51 of 205

Tilde expansion lets you write ~ as a short way to name a home directory. When Bash sees an unquoted ~ at the start of a word, it replaces it with the path of your home directory before the command runs, so ls ~/Documents becomes ls /home/ana/Documents. The same feature can name another user's home directory (~root) and the current and previous working directories (~+ and ~-).

Understanding the Concept

Every user account on a Linux or macOS system has a home directory, the folder where that user keeps personal files and settings. The path differs from user to user and from system to system: /home/ana on many Linux machines, /Users/ana on macOS, /root for the administrator account on most Linux systems. Typing the full path would make commands and scripts depend on one particular machine.

The tilde solves this. It stands for "the home directory of whoever is asking", so the same command works for every user. The important detail is that the expansion is done by the shell, not by the command. The command never sees the tilde:

echo ~
echo ~/notes.txt

Output (the home directory in these examples is /home/ana):

/home/ana
/home/ana/notes.txt
  • echo ~ received the single argument /home/ana.
  • In ~/notes.txt, the tilde was replaced and the rest of the word, /notes.txt, was kept as it was.
  • Neither command checked whether the file notes.txt exists. Tilde expansion only builds text.

The Forms of Tilde Expansion

FormExpands toWhere the value comes from
~Home directory of the current userThe HOME variable
~/pathThe home directory followed by /pathThe HOME variable
~nameHome directory of the user called nameThe system's user database
~+The current working directoryThe PWD variable
~-The previous working directoryThe OLDPWD variable

The first three forms are available in every POSIX shell. ~+ and ~- are Bash extensions.

How Bash Finds the Tilde Prefix

Bash looks at each word of a command. If the word starts with an unquoted tilde, the characters from the tilde up to the first unquoted slash (or the end of the word) form the tilde prefix. The characters after the tilde in the prefix are treated as a login name.

  • If the prefix is only ~, Bash uses the value of HOME.
  • If the prefix is ~name, Bash looks name up as a user account.
  • If the lookup fails, the word is left exactly as written.
  • If the lookup works, the prefix is replaced by the path, and the rest of the word is attached to it.

Because the prefix ends at the first slash, ~/projects/demo has the prefix ~, and ~root/.profile has the prefix ~root.

When Tilde Expansion Does Not Happen

Three situations leave the tilde alone.

The tilde is quoted. Quotes and backslashes turn off the special meaning:

echo "~"
echo '~/notes.txt'
echo \~
echo ~"/notes"

Output:

~
~/notes.txt
~
~/notes

The last command shows that even a quote placed directly after the tilde stops the expansion. The tilde prefix must contain no quoted characters.

The tilde is not at the start of a word. A tilde in the middle of a word is an ordinary character:

echo a~
echo a~/b
echo x~root

Output:

a~
a~/b
x~root

The name does not match any user. A word such as ~nosuchuser_xyz is printed as it was typed:

echo ~nosuchuser_xyz

Output:

~nosuchuser_xyz

Tilde Expansion in Variable Assignments

Assignments get one extra rule. In an assignment, Bash also expands a tilde that appears right after the = sign and right after every colon in the value. This is what makes lists of directories such as PATH convenient to write:

P=~/bin
echo "$P"
p=/usr/bin:~/bin:~/tools
echo "$p"

Output:

/home/ana/bin
/usr/bin:/home/ana/bin:/home/ana/tools

Both tildes in the second value were expanded, because each one follows a colon (or the equals sign). A common use is adding a personal directory to the front of PATH:

PATH=/usr/bin:/bin
export PATH=~/bin:$PATH
echo "$PATH"

Output:

/home/ana/bin:/usr/bin:/bin

Quoting the value switches this off, because the tilde is then inside quotes:

Q="~/bin"
echo "$Q"

Output:

~/bin

A subtle point is that Bash applies the assignment rule to words that only look like assignments when they are command arguments:

echo foo=~/bin
echo --dir=~/bin

Output:

foo=/home/ana/bin
--dir=~/bin

The first word has the shape name=value, so Bash treated the part after = as an assignment value. The second word starts with --dir, which is not a valid variable name, so its tilde was left alone. A script that needs the path in an option like --dir= should build it with a variable: --dir="$HOME/bin".

Home Directories of Other Users

Writing a user name directly after the tilde gives that user's home directory, as recorded in the system's user database:

echo ~root
echo ~root/.profile

Output (on most Linux systems):

/root
/root/.profile

The paths printed depend on the machine. The administrator's home directory is /root on most Linux systems but differs on other systems such as macOS.

The Current and Previous Directory: ~+ and ~-

Bash keeps the path of the current directory in PWD and of the previous one in OLDPWD. The forms ~+ and ~- expand to those values:

cd /tmp
cd /var
echo ~+
echo ~-

Output:

/var
/tmp

~+ is the same as $PWD, and ~- is the same as $OLDPWD. Before any cd has happened, OLDPWD is unset, and ~- is then left unchanged as the text ~-.

The command cd - uses the same idea. It changes to the previous directory and prints its path.

Where the Home Directory Comes From

For a plain ~, Bash reads the HOME variable. If you change HOME, the tilde follows:

HOME=/srv/demo
echo ~
echo ~/x

Output:

/srv/demo
/srv/demo/x

If HOME is unset, Bash does not give up. It falls back to the home directory recorded for the current user in the system's user database. For the administrator account in a typical Linux system, echo ~ prints /root even after unset HOME.

The result of a tilde expansion is treated as if it were quoted, so it is never split into several words, even if the directory name contains a space:

HOME='/home/my user'
printf '[%s]\n' ~
printf '[%s]\n' ~/x

Output:

[/home/my user]
[/home/my user/x]

Each command received one argument.

Why a Variable Cannot Build a Tilde Prefix

Tilde expansion happens early, before Bash expands variables. This order has a visible effect: a variable's value cannot be used to make a tilde prefix.

user=root
echo ~$user
eval echo ~$user

Output:

~root
/root

When Bash processed ~$user, the word did not yet contain a valid user name; it contained the text $user, which is not a login name. The tilde was left alone, and the variable was expanded afterwards, which produced the text ~root. By then the tilde step had already finished. The eval version works because eval runs the whole line through the expansions a second time, but eval carries serious risks that a later lesson on security explains. A safer alternative is to ask the system for the directory with a command such as getent passwd root, or simply to avoid building user paths from variables.

Tilde Compared with $HOME

For the current user's home directory, ~ and $HOME give the same result. They differ in where they work:

  • A tilde is expanded only when it is unquoted and at the start of a word (or after = or : in assignments).
  • $HOME is expanded in most places, including inside double quotes.

This matters for paths that contain spaces. Inside double quotes the tilde does not expand, but $HOME does:

printf '[%s]\n' "$HOME/my docs"
printf '[%s]\n' ~/"my docs"
printf '[%s]\n' "~/my docs"

Output:

[/home/ana/my docs]
[/home/ana/my docs]
[~/my docs]

The first command quotes everything and uses $HOME. The second leaves the tilde outside the quotes and quotes only the part with the space, so the path stays one word. The third quotes the tilde as well, so nothing is expanded.

Practical Applications

Combining Tilde with Wildcards

Tilde expansion runs before filename expansion, so a home directory can be combined with a wildcard:

echo ~/*.txt

Output (if the home directory contains a.txt and b.txt):

/home/ana/a.txt /home/ana/b.txt

Bash first replaced ~ with the home path and then expanded the pattern against the files in that directory.

Moving Around and Copying Files

cd ~
cd
cp report.txt ~/backup/
mkdir -p ~/projects/demo
  • cd ~ and plain cd both change to the home directory.
  • cp report.txt ~/backup/ copies a file into a folder in the home directory, from any current directory.
  • mkdir -p ~/projects/demo creates a nested path under the home directory.

Using $HOME in Scripts

Inside scripts, paths are often built with variables and quotes, which makes $HOME the natural choice:

backup_dir="$HOME/backups"
mkdir -p "$backup_dir"
echo "Saving to $backup_dir"

Output:

Saving to /home/ana/backups

The same line written with a tilde in quotes, "~/backups", would have produced the literal text ~/backups, creating a directory named ~ in the current folder.

Availability in Other Shells

~ and ~name work in every POSIX shell, including Dash, the shell that /bin/sh points to on Debian and Ubuntu. The extensions ~+ and ~- are Bash features. In Dash, echo ~+ prints the text ~+.

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 Tilde Expansion and Home Directories and get answers drawn from it.

Signed-in readers only.