0
0
Bash Scriptingscripting~5 mins

Tilde expansion (~) in Bash Scripting

Choose your learning style9 modes available
Introduction

Tilde expansion lets you quickly use your home folder path without typing the full address.

When you want to access files in your home directory easily.
When writing scripts that should work on any user's home folder.
When setting environment variables that point to your home directory.
When navigating quickly in the terminal to your home or other users' home folders.
Syntax
Bash Scripting
echo ~
echo ~username

The tilde (~) alone means your current user's home directory.

Using ~username expands to that user's home directory if you have permission.

Examples
Prints the path to your home directory.
Bash Scripting
echo ~
Changes directory to the Documents folder inside your home directory.
Bash Scripting
cd ~/Documents
Lists files in the home directory of 'otheruser' if accessible.
Bash Scripting
ls ~otheruser
Sample Program

This script prints the tilde symbol, then the expanded home directory path, and finally lists the first three files or folders in your home directory.

Bash Scripting
#!/bin/bash

# Show current user's home directory
echo "My home is: ~"

# Show expanded home directory
echo "Expanded home is: $HOME"

# List files in home directory using tilde
ls ~ | head -3
OutputSuccess
Important Notes

Tilde expansion happens only at the start of a word in the shell.

If you put quotes around ~, it won't expand.

Not all shells support tilde expansion the same way; bash does.

Summary

Tilde (~) is a shortcut for your home directory.

Use ~username to refer to other users' home directories.

Tilde expansion helps write shorter, portable scripts.