How to Use Tilde Expansion in Bash [4 Practical Cases]

Tilde expansion is a feature in Bash that allows users to use the tilde character (~) as equivalent to a certain path. This is particularly useful for quickly navigating to user’s home directory or directories relative to the home directory. Moreover, one user can switch to another user’s home directory using this tilde expansion. This article is intended to clear your idea about tilde expansion in Bash.

Key Takeaways

  • Expanding HOME variable using tilde expansion.
  • Changing to last visited directory using tilde.
  • Accessing the directory stack using tilde expansion.

Free Downloads

What is Tilde Expansion?

The tilde(~) character is typically located in the top-left corner of the keyboard, to the left of the number “1” key and above the “Tab” key. It has a special meaning to Bash shell. It’s a shorthand notation for representing user’s home directory. This shortcut is quite useful when changing directories from the command line.

4 Different Cases of Tilde Expansion in Bash

Tilde expansion is mainly used for changing directory to home directory. However, this expansion has other usage also. One can go to other user’s home directory, access directory from the directory stack and go back to previous working directory using tilde expansion.

Case 1: Expanding HOME Variable and User’s Home Directory Using Tilde in Bash

In Bash, the tilde (~) symbol takes users to their home directory, which is determined by the HOME environment variable.

Open your terminal and run the command below:

echo ~

Getting the home directory using tilde expansionIt indicates that tilde refers “/home/laku”. This should be exactly the current value of the HOME variable. To cross check, call the variable from the command line using the following command:

echo $HOME

Tilde expansion is equivalent to HOME variableAs you see, the value of the environment variable HOME is currently “/home/laku”. So tilde always refers to the value of HOME variable. Let’s change the value of the HOME using the export command.

export HOME=/usr

The new value of the HOME variable is set as “/usr”.Setting new HOME variableLet’s land on the new HOME using the tilde sign. After that, check the directory name using pwd command.

cd ~
pwd

Changing directory using tilde expansionAs you see, tilde refers to “/usr” exactly what is set in the HOME variable now. However, home variable may not be set in the shell. Hence, tilde can’t refer to the HOME variable. In that case, it refers to home directory of the current user. Let’s unset the HOME variable and check it again.

unset HOME
echo $HOME
echo ~
cd ~

Unsetting HOME variableIt shows that nothing is set in the HOME variable. But the tilde sign refers the current user home directory which is “/home/laku”. In a word, tilde refers to the HOME variable, However, if HOME variable is not set it refers the current user’s home directory.

Creating Files in a Directory Using Tilde Expansion

As previously mentioned, it’s evident that tilde expansion allows one to navigate relative to their home directory. Utilizing tilde expansion makes the process of generating files within a specific directory quite straightforward. Let’s visualize the idea in a script.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file named createfiles.sh in the build-in nano editor:

nano bexpansion.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • createfiles.sh: Name of the file.
Creating a Bash script file❸ Copy the following scripts and paste them into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

Script (createfiles.sh) >

#!/bin/bash

# Define the path to the "January" directory using tilde expansion
january_directory=~/January

# Check if the "January" directory exists
if [ ! -d "$january_directory" ]; then
# If it doesn't exist, create it
mkdir -p "$january_directory"
fi

# Create the "record.txt" file inside the "January" directory
touch "$january_directory/record.txt"
echo "File 'record.txt' created in $january_directory."
EXPLANATION

#!/bin/bash” specifies that the script should be interpreted and run using the Bash shell.

Then it creates a file named “record.txt” within a directory named “January” located in the user’s home directory. The script checks if the “January” directory exists; if not, it creates it using mkdir command. Following this, the script utilizes the touch command to create the “record.txt” file within the “January” directory. Finally, it provides feedback to the user by printing a message confirming the successful creation of “record.txt” in the specified directory.

❹ Use the following two commands to make the file executable:

chmod u+x createfiles.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • createfiles.sh: Name of the script.
Changing permission of a Bash scriptRun the script by the following command:
./createfiles.sh

Creating files using tilde expansionThe program successfully creates the “record.txt” file in the folder “/home/laku/January”. It uses tilde expansion to expand the home directory which is “home/laku”.

Case 2: Expanding Current and Previous Working Directory

Using tilde sign, one can expand the current or the previous working directory. One needs to put a plus(+) or minus() after tilde sign to expand current and previous working directory respectively. It works no matter the HOME variable is set or not.

For instance, currently I am in my home directory which is “/home/laku”. Let’s go to the “/usr” directory for example. Now, run the following command:

echo ~+

Expanding current directory using tildeAs you see “~+” echoes the current working directory and the result is exactly what the pwd command retrieves. Because “~+” takes the value of the PWD environment variable.

However, if you place a minus after the tilde sign, it will take you to the previous working directory.

cd ~-

Expanding previous directory using tilde expansion in BashIt shows “~-” land on “/home/laku” directory as it was the previous working directory before moving to “/usr”. “~-” takes the value of the environment variable namely OLDPWD.

Case 3: Directly Expand Other User’s Home Directory Using Tilde Expansion in Bash

One can directly go to another user’s home directory by adding name of the user after the tilde sign. Let’s first create a user named “kelly” using the adduser command.Adding new userNow, I want to go to kelly’s home directory. To go there first I need to switch to user kelly using the su command.Switching to the new userSo the current user has changed to kelly. But I am still on laku’s home directory. To land on kelly’s home directory simply put the username after the tilde sign.

cd ~kelly

Changing to another user's home directory using tilde expansion in BashAs you can see current directory is changed to kelly’s home directory from laku’s home directory. You don’t need to be at the home directory of the user from which you want to land to the other user’s home. This works no matter in which location you are currently on the system.

Case 4: Accessing Directory from Directory Stack Using Tilde Expansion in Bash

Bash has a directory stack that can be accessed using the dirs command. You can push a directory in the directory stack using the pushd command. Otherwise, it is filled with the latest visited directory only. Importantly, one can access the items of directory stack using tilde expansion. Let me push some directories in the directory stack and visualize it using dirs command.

pushd /home/laku/Desktop/
pushd /home/laku/Downloads/
pushd /home/laku/Documents/
dirs

Pushing directories in the directory stackYou can see there are four items or directories in the directory stack. Now, all these items can be accessed using the tilde expansion. One needs to put the item index after the tilde sign. However, keep in mind that indexing starts from “0”.

First of all, to get the first item from the directory stack run the following command.

echo ~0

Furthermore, to get the third item from the stack put 2 after the tilde sign.

echo ~2

Accessing directory from directory stack using tilde expansion in BashMoreover, one can access the stack in reverse order as well. Placing a minus before the index number of the directory makes the command traverse the list from right to left. For instance, to get the second directory from the right, you can put “-1” instead of “2” after the tilde sign.Accessing directory from reverse direction using the tilde expansion in Bash

Conclusion

In conclusion, there are different uses of Bash tilde expansion. All of these are related to changing directories quickly and efficiently. I believe from now you can employ those techniques to move around directories.

People Also Ask

How to disable tilde in Bash?
You can use backslash to disable tilde expansion. For example, in “\~ backslash prevent tilde expansion by the shell.  
Echoing tilde to a file without expanding it in Bash?
Use double or single quote to write tilde to a file without replacing it by the home directory.
Why tilde is not expanded in a Bash script?
It seems you enclose tilde with quote. To expand the home directory within quote use $HOME environment variable instead of tilde. However, if you want the tilde sign to work then remove any double quote or single quote that encloses it. 
Why tilde doesn’t expand inside a double or single quote?
Inside the double quote tilde has no meaning and used as a literal. According to POSIX standard all characters are treated as literal inside the double quote except dollar sign, backtick, backslash and parameter ‘@

Related Articles


<< Go Back to An Overview of Shell Expansion in Bash | Bash Scripting Tutorial 

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment