Course contentsShow
← Linux
Lesson 240 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Tilde Expansion Rules

Handle complex path shortcuts reliably in user-specific contexts.

Mastering Tilde Expansion Rules

In this lesson, you will learn how to use the tilde (~) character as a reliable, context-aware shortcut to navigate to specific user directories within your scripts.

The Power of the Tilde

In Bash, the tilde is more than just a symbol; it is an operator that tells the shell to resolve a path based on user identity. When you type ~, the shell performs "Tilde Expansion" to replace that character with the absolute path of your current user's home directory.

The real power appears when you need to reference other users or specific system locations. The shell follows strict rules for these expansions:

  1. ~ by itself: Expands to the value of your $HOME environment variable.
  2. ~username: Expands to the home directory of the specified user (e.g., ~root expands to /root).
  3. ~+: Expands to the current working directory (identical to the $PWD variable).
  4. ~-: Expands to the previous working directory (the one you were in before your last cd command).

Reliable Context Handling

Why use these shortcuts instead of hardcoded paths like /home/alice/docs? Because they are portable. If you write a script that processes files in a user’s home directory, using ~/data ensures the script works correctly regardless of whether the user is named alice, bob, or admin.

Consider this example of moving a configuration file:

# Move a config file to the current user's home directory
mv ./my_config.conf ~/configs/

# Reference another user's public directory safely
cp ~/project/readme.txt ~bob/public_html/

Important Rule: The Position Constraint

For tilde expansion to work, the ~ must appear at the start of a word or immediately following an assignment operator (like PATH=~/bin). If you place the tilde in the middle of a string—for example, echo "The path is ~/myfolder"—it will expand correctly, but if you put it after a colon, such as PATH=/opt/bin:~/bin, the shell will treat it as a literal tilde character rather than a path shortcut. Always keep your tildes at the beginning of the path segment to ensure the shell resolves them correctly.

Key Takeaway: Tilde expansion is a dynamic, user-specific shortcut that simplifies path management by automatically resolving to home directories or navigation history without relying on hardcoded absolute paths.