Understanding the ln
Command in Linux: Creating Hard and Symbolic Links
1. Introduction
The command’s name, ln
, stands for “link. It is a fundamental utility for creating links between files or directories, enabling multiple access points to the same data. It supports two types of links:
- Hard Links: Additional names for the same file data, sharing the same inode (a unique identifier for file metadata and data blocks). They are restricted to the same filesystem and cannot link to directories.
- Symbolic Links (Symlinks): Special files containing a path to another file or directory, acting as shortcuts. They can span filesystems, link to directories, and may become “broken” if the target is moved or deleted.
A Quick Recap of Linux Filesystem: Inodes, Directory Entries
Before exploring the ln
command for creating links, it’s essential to understand how files are structured in Linux.
The Linux filesystem is like a tree that arranges files and folders in a structured order. At its heart are inodes and directory entries, which work together to manage files. Understanding these helps explain how hard links and symbolic links function.
1. The Core: Inodes and Data
- Inode (Index Node):
-
Every file in a Unix-like filesystem is represented by an inode (short for “index node”), which is a unique identifier in the filesystem.
-
Think of an inode as the actual file’s ID card on the filesystem.
-
Each file and directory has a unique inode number (within a given filesystem).
-
It stores metadata about the file:
- File type (regular file, directory, link, etc.)
- Permissions (read, write, execute)
- Owner and group IDs
- File size
- Timestamps (access, modification, change)
- Pointers to the data blocks where the file’s actual content is stored on the disk.
- A “link count” (number of hard links pointing to this inode).
-
Crucially, the inode does NOT store the filename.
-
Use the command
ls -i filename
to view the inode number of a file, andstat filename
to view the metadata stored in the inode -
Example:
# Create an empty file named example.txt $ touch example.txt # Display the inode number of example.txt $ ls -i example.txt 12345 example.txt # Display detailed metadata of example.txt $ stat example.txt File: example.txt Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 801h/2049d Inode: 12345 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 1000/ user) Gid: ( 1000/ user) Access: 2023-10-01 12:00:00.000000000 +0000 Modify: 2023-10-01 12:00:00.000000000 +0000 Change: 2023-10-01 12:00:00.000000000 +0000 Birth: 2024-10-01 12:25:00.000000000 +0000
(Inode
12345
stores all info aboutmy_document.txt
except its name)This output shows:
- Inode number: 12345
- Size: 0 bytes (the file is empty)
- Blocks: 0 (no data blocks allocated)
- Permissions: -rw-r—r— (readable and writable by the owner, readable by others)
- Owner: user (UID 1000)
- Group: user (GID 1000)
- Timestamps: Access, modification, and change times
- Inode number: 12345
- Links: 1 (number of hard links)
-
How Inodes Work:
(i) When you create a file, the file system:
- Allocates an inode to store the file’s metadata. (owner and group IDs, permissions (mode), timestamps (creation, modification, access), link count, size, and pointers to data blocks)
- Allocates data blocks to store the file’s content. These are the actual disk blocks (or extents) where file contents are stored.
- Creates a directory entry that links the file name to the inode number. A name → inode number mapping is added to the parent directory.
(ii) When you access a file, the system:
- Looks up the file name in the directory to find the corresponding inode number i.e. filename → inode number
- Uses the inode number to locate the inode, which contains the metadata and pointers to the data blocks.
- Retrieves the data from the data blocks.
- This separation of metadata (in the inode) and content (in data blocks) allows for efficient file management and features like hard links.
-
2. Connecting Names to Files: Directory Entries
- Directory: A special type of file whose content is a list of directory entries.
- Directory Entry: Each entry maps a filename to an inode number.
- It’s like an address book entry:
Filename --> Inode Number
.
- It’s like an address book entry:
- How it works: When you access
my_document.txt
:- The system looks in the current directory file for the entry “my_document.txt”.
- It finds the associated inode number (e.g.,
12345
). - It then uses inode
12345
to find the metadata and the actual data blocks. - Directory entries are the crucial link between the human-readable filename and the system-internal inode.
1.1. Hard Links: Multiple Names for the Same File Data
- Definition: A hard link creates an additional directory entry (another filename) that points to the exact same inode as an existing file.
- Characteristics:
- Shared Inode: The original filename and all its hard links share the same inode. This means they share the same metadata (permissions, timestamps) and the same data blocks.
- Indistinguishable: Once created, a hard link is just another name for the file; there’s no “original” vs. “link” distinction at the inode level.
- Same Filesystem Only: Hard links cannot span across different filesystems/partitions because inode numbers are unique only within a single filesystem.
- Files Only (Generally): You typically cannot create hard links to directories (to prevent filesystem loops).
- Data Persistence: If the original file is deleted, the data remains accessible through the hard link because the inode and data blocks persist until all hard links are removed.
- Link Count: The inode stores a “link count.” Creating a hard link increments this count. Deleting a filename (any hard link) decrements it. The file’s data is only removed from disk when the link count drops to 0 (and no process is using the file).
- Creation:
# Create a hard link named HARD_LINK_NAME to TARGET_FILE $ ln TARGET_FILE HARD_LINK_NAME
- Example:
# Create an original file with content $ echo "Initial content" > original.txt # Display the inode number of original.txt $ ls -i original.txt 12345 original.txt # Create a hard link named hard_link.txt to original.txt $ ln original.txt hard_link.txt # Display inode numbers of both files to show they are the same $ ls -i original.txt hard_link.txt 12345 original.txt 12345 hard_link.txt # Same inode number! # Check the link count using stat $ stat original.txt | grep Links Links: 2 # Alternatively, check the link count using ls -l $ ls -l original.txt -rw-r--r-- 2 user user 16 May 3 21:00 original.txt # Link count is 2 # Append more content to the hard link $ echo " -More content" >> hard_link.txt # Show that the original file reflects the change $ cat original.txt Initial content -More content # Delete the original file $ rm original.txt # Show that the data is still accessible via the hard link because link count was > 0 $ cat hard_link.txt Initial content -More content # Check the updated link count $ stat hard_link.txt | grep Links Links: 1 # Link count decremented
1.2. Symbolic Links (Symlinks/Soft Links): Pointers to Paths
- Definition: A symbolic link is a special type of file whose content is simply the path string (relative or absolute) to another file or directory (the target). It acts like a shortcut or an alias.
- Characteristics:
- Separate Inode: A symbolic link has its own, distinct inode number and file type (
l
). - Path-Based Reference: A symlink stores the path to the target (e.g.,
/path/to/original.txt
), not the actual data. It has its own inode, separate from the target. - Cross-Filesystem Flexibility: Because it stores a path, it can point to targets on different filesystems.
- Directory Linking: Unlike hard links, symlinks can reference directories, making them useful for creating shortcuts to folders.
- Risk of Being Broken (Dangling): If the target file/directory is moved, renamed, or deleted, the symbolic link still exists but becomes “broken” – it points to a non-existent location.
- Permissions: The permissions displayed for a symlink (e.g.,
lrwxrwxrwx
) are generally not used for access control. Access is determined by the permissions of the target file/directory.
- Separate Inode: A symbolic link has its own, distinct inode number and file type (
- Creation:
# Create a symbolic link named SYMLINK_NAME pointing to TARGET_PATH $ ln -s TARGET_PATH SYMLINK_NAME
- Example:
# Create an original file with content $ echo "Target data" > target_file.txt # Display the inode number of target_file.txt $ ls -i target_file.txt 23456 target_file.txt # Create a symbolic link named symlink_file.txt pointing to target_file.txt $ ln -s target_file.txt symlink_file.txt # Display detailed information of both files to show different inodes and link type $ ls -li target_file.txt symlink_file.txt 23456 -rw-r--r-- 1 user user 12 May 3 21:05 target_file.txt 23457 lrwxrwxrwx 1 user user 15 May 3 21:05 symlink_file.txt -> target_file.txt # Different inode, 'l' type, shows target # Access the symlink to read the target's content $ cat symlink_file.txt Target data # Create a directory named my_data_dir $ mkdir my_data_dir # Create a symbolic link named data_shortcut pointing to my_data_dir $ ln -s my_data_dir data_shortcut # Display the symbolic link to the directory $ ls -ld data_shortcut lrwxrwxrwx 1 user user 11 May 3 21:06 data_shortcut -> my_data_dir/ # Delete the original target file $ rm target_file.txt # Attempt to access the broken symlink $ cat symlink_file.txt cat: symlink_file.txt: No such file or directory # Display the broken symlink (often shown in red by ls) $ ls -l symlink_file.txt # Often shown in red by ls lrwxrwxrwx 1 user user 15 May 3 21:05 symlink_file.txt -> target_file.txt
1.3. Key Differences & Connections Summarized
Feature | Hard Link | Symbolic Link (Symlink) |
---|---|---|
Definition | Additional name for the same file data | Special file containing a path to a target |
Inode | Shares the same inode as the original | Has its own inode, separate from the target |
Points To | Same Inode (same data & metadata) | A Path String (to target file/directory) |
References | Same inode as target | Pathname string |
Filesystem Scope | ❌ Must be on the same filesystem as target | ✅ Can span across different filesystems |
Target Type | Generally files only | Files or Directories |
Directory Support | ❌ Generally cannot link to directories | ✅ Can link to directories |
Iehavior if Target Deleted | Data remains if other hard links exist | Link becomes “broken” or “dangling” the target is removed |
Disk Space Overhead | Minimal (one directory entry) | Size of pathname stored in symlink file |
Link Count Visible | Yes (shown in ls -l link count column) | No |
ls -l Link Count | Increments link count of the target’s inode | Does not affect target’s link count |
Creation Command | ln source dest | ln -s source dest |
Use Case | Robust aliasing within a filesystem | Flexible shortcuts and mount-point indirection |
How they connect:
- Inode: The central piece holding file metadata and data pointers.
- Directory Entry: Maps a human-readable filename to an inode number.
- Hard Link: Creates an additional directory entry mapping a new filename to an existing inode.
- Symbolic Link: Creates a new file (with its own inode) whose data content is the path string to another file/directory. When the symlink is accessed, the system reads this path and then accesses the target.
This structure provides both robust data referencing (hard links) and flexible shortcut capabilities (symbolic links) within the Linux filesystem.
2. Basic Syntax
The ln
command offers flexible syntax depending on the task:
-
Creating a single link (hard or symbolic):
# Create a link (hard by default) named LINK_NAME to TARGET $ ln [OPTION]... TARGET LINK_NAME
TARGET
: The existing file or directory to link to.LINK_NAME
: The name of the new link.
-
Creating links for multiple files in a directory:
# Create links for each TARGET in DIRECTORY with the same basenames $ ln [OPTION]... TARGET... DIRECTORY
TARGET...
: One or more files to link.DIRECTORY
: The directory where links will be created with the same basenames as the targets.
-
Specifying the target directory first:
# Create links for each TARGET in DIRECTORY $ ln [OPTION]... -t DIRECTORY TARGET...
- Useful for linking multiple files into a specific directory.
By default, ln
creates hard links. Use the -s
option to create symbolic links. Options like -f
(force) or -v
(verbose) modify behavior, as detailed later.
3. Core Use Cases with Examples
To illustrate the ln
command’s functionality, let’s set up a test environment:
# Create a test directory named ln_test
$ mkdir ln_test
# Navigate into the test directory
$ cd ln_test
# Create a file named file1.txt with content
$ echo "Original content for file1." > file1.txt
# Create another file named file2.log with content
$ echo "Content for file2." > file2.log
# Create a subdirectory named test_dir
$ mkdir test_dir
# Create a file inside test_dir with content
$ echo "File inside directory." > test_dir/inner.txt
# List the directory contents with inode numbers to verify setup
$ ls -li
total 12
123456 -rw-r--r-- 1 user user 28 May 12 20:00 file1.txt
123457 -rw-r--r-- 1 user user 19 May 12 20:00 file2.log
123458 drwxr-xr-x 2 user user 4096 May 12 20:00 test_dir
3.1. Creating a Hard Link
Hard links create additional names for the same file data, useful for maintaining multiple access points within the same filesystem.
Input:
# Create a hard link named hardlink.txt to file1.txt
$ ln file1.txt hardlink.txt
Output:
# List the directory to show the hard link
$ ls -li
total 16
123456 -rw-r--r-- 2 user user 28 May 12 20:00 file1.txt
123456 -rw-r--r-- 2 user user 28 May 12 20:00 hardlink.txt
123457 -rw-r--r-- 1 user user 19 May 12 20:00 file2.log
123458 drwxr-xr-x 2 user user 4096 May 12 20:00 test_dir
Explanation:
- Both
file1.txt
andhardlink.txt
share the same inode (123456) and have a link count of 2. - Modifying
hardlink.txt
also changesfile1.txt
since they point to the same data.
3.2. Creating a Symbolic Link to a File
Symbolic links are pointers to files, ideal for creating shortcuts or linking across filesystems.
Input:
# Create a symbolic link named symlink.log pointing to file2.log
$ ln -s file2.log symlink.log
Output:
# List the directory to show the symbolic link
$ ls -li
total 16
123456 -rw-r--r-- 2 user user 28 May 12 20:00 file1.txt
123456 -rw-r--r-- 2 user user 28 May 12 20:00 hardlink.txt
123457 -rw-r--r-- 1 user user 19 May 12 20:00 file2.log
123458 drwxr-xr-x 2 user user 4096 May 12 20:00 test_dir
123459 lrwxrwxrwx 1 user user 8 May 12 20:00 symlink.log -> file2.log
Explanation:
symlink.log
has a unique inode (123459) and points tofile2.log
.- The link’s size (8 bytes) reflects the length of the target path.
3.3. Creating a Symbolic Link to a Directory
Symbolic links can point to directories, making them useful for accessing nested directories.
Input:
# Create a symbolic link named symlink_dir pointing to test_dir
$ ln -s test_dir symlink_dir
Output:
# List the directory to show the symbolic link
$ ls -li
total 16
123456 -rw-r--r-- 2 user user 28 May 12 20:00 file1.txt
123456 -rw-r--r-- 2 user user 28 May 12 20:00 hardlink.txt
123457 -rw-r--r-- 1 user user 19 May 12 20:00 file2.log
123458 drwxr-xr-x 2 user user 4096 May 12 20:00 test_dir
123459 lrwxrwxrwx 1 user user 8 May 12 20:00 symlink.log -> file2.log
123460 lrwxrwxrwx 1 user user 8 May 12 20:00 symlink_dir -> test_dir
# List the contents of the symbolic link to verify it points to the directory
$ ls symlink_dir/
inner.txt
Explanation:
symlink_dir
points totest_dir
, allowing access to its contents.
3.4: Linking Multiple Files into a Directory
In this example, we demonstrate how to create symbolic links to multiple files inside a directory on an Ubuntu system, starting in the user’s home directory (~
). We’ll show an initial setup, an incorrect method that fails, and two correct methods using relative and absolute paths.
3.4.1 Initial Setup
Start by creating a directory ln_test
(if not already created) and navigating into it:
# Create a directory named ln_test
$ mkdir ln_test
# Navigate into ln_test
$ cd ln_test
Create two files, file1.txt
and file2.log
, with some content:
# Create file1.txt with content
$ echo "Original content for file1." > file1.txt
# Create file2.log with content
$ echo "content for file2." > file2.log
Verify the files are created:
# List the files to verify
$ ls
file1.txt file2.log
Create a subdirectory link_collection
:
# Create a subdirectory named link_collection
$ mkdir link_collection
Check the directory structure with ls -lRi
:
# List the directory structure recursively with inode numbers
$ ls -lRi
.:
total 12
1188231 -rw-rw-r-- 1 user user 28 May 13 03:03 file1.txt
1188232 -rw-rw-r-- 1 user user 19 May 13 03:03 file2.log
1188233 drwxrwxr-x 2 user user 4096 May 13 03:04 link_collection
./link_collection:
total 0
This confirms that link_collection
is an empty subdirectory within ~/ln_test
.
3.4.2 Incorrect Method: Creating Self-Referential Symbolic Links
Now, attempt to create symbolic links inside link_collection
using bare filenames:
# Incorrect method: Create symbolic links that may point to themselves
$ ln -s file1.txt file2.log link_collection/
This command creates symbolic links named file1.txt
and file2.log
inside link_collection
, but the targets are specified as “file1.txt” and “file2.log”. Since these are relative paths, they are resolved relative to the link’s location (link_collection/
), making the links point to themselves.
Check the links:
# List the links inside link_collection
$ ls -li link_collection/
total 0
1188234 lrwxrwxrwx 1 user user 9 May 13 03:05 file1.txt -> file1.txt
1188235 lrwxrwxrwx 1 user user 9 May 13 03:05 file2.log -> file2.log
Note that files names file1.txt -> file1.txt
and file2.log -> file2.log
are often shown in red in this case.
Try to access one of the links:
# Attempt to access the self-referential link
$ cat link_collection/file1.txt
cat: link_collection/file1.txt: Too many levels of symbolic links
Explanation:
- The link
link_collection/file1.txt
points tofile1.txt
, which is interpreted aslink_collection/file1.txt
(itself) due to the relative path. - This creates an infinite loop during resolution, and the system halts it with the “Too many levels of symbolic links” error.
3.4.3 Correct Method 1: Using Relative Paths
To fix this, use relative paths that point to the files in the parent directory (~/ln_test
). First, clean up the incorrect links:
# Remove the incorrect self-referential links
$ rm link_collection/file1.txt link_collection/file2.log
Create new symbolic links with relative paths:
# Create a symbolic link to file1.txt using a relative path
$ ln -s ../file1.txt link_collection/file1.txt
# Create a symbolic link to file2.log using a relative path
$ ln -s ../file2.log link_collection/file2.log
Verify the links:
# List the links to verify
$ ls -li link_collection/
total 0
1188236 lrwxrwxrwx 1 user user 12 May 13 03:06 file1.txt -> ../file1.txt
1188237 lrwxrwxrwx 1 user user 12 May 13 03:06 file2.log -> ../file2.log
Test accessing the links:
# Access the link to file1.txt to verify it works
$ cat link_collection/file1.txt
Original content for file1.
# Access the link to file2.log to verify it works
$ cat link_collection/file2.log
content for file2.
Explanation:
../file1.txt
instructs the system to go up one level (to~/ln_test
) and findfile1.txt
.- This correctly links to the original file, avoiding self-reference and enabling proper access.
3.4.4 Correct Method 2: Using Absolute Paths
Alternatively, use absolute paths to ensure the links always point to the correct files, even if link_collection
is moved. First, remove the previous links:
# Remove the previous relative path links
$ rm link_collection/file1.txt link_collection/file2.log
Get the absolute path of the current directory and create the links:
# Set TARGET_DIR to the current working directory's absolute path
$ export TARGET_DIR=$(pwd)
# Create a symbolic link to file1.txt using an absolute path
$ ln -s "$TARGET_DIR/file1.txt" link_collection/file1.txt
# Create a symbolic link to file2.log using an absolute path
$ ln -s "$TARGET_DIR/file2.log" link_collection/file2.log
# OR use following one line command
# ln -s "$(pwd)/file1.txt" "$(pwd)/file2.log" link_collection/
# Or specify the full path directly, e.g.:
# ln -s /home/user/Desktop/rmdir_test_area/file1.txt link_collection/file1.txt
Verify the links:
# List the links to verify
$ ls -li link_collection/
total 0
1188238 lrwxrwxrwx 1 user user 45 May 13 03:07 file1.txt -> /home/user/ln_test/file1.txt
1188239 lrwxrwxrwx 1 user user 45 May 13 03:07 file2.log -> /home/user/ln_test/file2.log
Test accessing the links:
# Access the link to file1.txt to verify it works
$ cat link_collection/file1.txt
Original content for file1.
# Access the link to file2.log to verify it works
$ cat link_collection/file2.log
content for file2.
Explanation:
- Absolute paths (e.g.,
/home/user/ln_test/file1.txt
) explicitly specify the full location of the target files. - This method is robust against directory movement but requires the target files to remain at their original locations.
3.4.5 Summary
- Incorrect Method:
ln -s file1.txt file2.log link_collection/
creates self-referential links, causing an infinite loop and the “Too many levels of symbolic links” error. - Correct Method 1: Use relative paths (e.g.,
../file1.txt
) to reference files in the parent directory. - Correct Method 2: Use absolute paths (e.g.,
/home/user/ln_test/file1.txt
) for location-independent links.
Understanding path resolution in symbolic links is key to avoiding errors and ensuring links work as intended.
4. Key Options Explained (with Examples)
4.1. -s, --symbolic
: Create a Symbolic Link
- Purpose: Specifies that a symbolic link should be created instead of a hard link.
- Syntax:
ln -s TARGET LINK_NAME
Input:
# Create a symbolic link named passwd_link pointing to /etc/passwd
$ ln -s /etc/passwd passwd_link
Output:
# List the symbolic link
$ ls -l passwd_link
lrwxrwxrwx 1 user user 11 May 12 20:00 passwd_link -> /etc/passwd
4.2. -f, --force
: Force Overwrite
- Purpose: Removes an existing destination file before creating the link.
- Syntax:
ln -f [OTHER_OPTIONS] TARGET LINK_NAME
Input:
# Create a file named old.txt with content
$ echo "Old content" > old.txt
# Create an empty file named new.txt
$ touch new.txt
# Create a symbolic link named existing_link pointing to new.txt
$ ln -s new.txt existing_link
# Create or update a symbolic link named existing_link to old.txt, overwriting if it exists
$ ln -sf old.txt existing_link
Output:
# List the symbolic link to verify it points to old.txt
$ ls -l existing_link
lrwxrwxrwx 1 user user 7 May 12 20:00 existing_link -> old.txt
4.3. -i, --interactive
: Prompt Before Overwriting
- Purpose: Prompts for confirmation before overwriting an existing file.
- Syntax:
ln -i [OTHER_OPTIONS] TARGET LINK_NAME
Input:
# Create a file named config.txt with content
$ echo "Existing" > config.txt
# Display the content of config.txt
$ cat config.txt
Existing
# Create a file named new_config.txt with content
$ echo "New Config" > new_config.txt
# Display the content of new_config.txt
$ cat new_config.txt
New Config
# Create a hard link named config.txt to new_config.txt, prompting before overwrite
$ ln -i new_config.txt config.txt
Output:
# Since config.txt already exists, it prompts for confirmation
ln: replace 'config.txt'? y
# Display the content of new_config.txt
$ cat new_config.txt
New Config
# Display the content of config.txt (now linked to new_config.txt)
$ cat config.txt
New Config
4.4. -n, --no-dereference
: Treat LINK_NAME as a File
- Purpose: Treats
LINK_NAME
as a file, even if it’s a symlink to a directory, preventing links from being created inside the target directory. - Syntax:
ln -nfs NEW_TARGET EXISTING_SYMLINK
Input:
# Create a directory named dir1
$ mkdir dir1
# Create an empty file named file.txt
$ touch file.txt
# Create a symbolic link named link_to_dir pointing to dir1
$ ln -s dir1 link_to_dir
# Check the link
$ ls -l link_to_dir
lrwxrwxrwx 1 user user 8 May 12 20:00 link_to_dir -> dir1
# Update the symbolic link link_to_dir to point to file.txt, treating it as a file, , overwriting any existing link (-f) and preventing directory content linking (-n)
$ ln -sfn file.txt link_to_dir
Output:
# List the updated symbolic link
$ ls -l link_to_dir
lrwxrwxrwx 1 user user 8 May 12 20:00 link_to_dir -> file.txt
4.5. -v, --verbose
: Verbose Output
- Purpose: Prints the name of each linked file for confirmation.
- Syntax:
ln -v [OTHER_OPTIONS] TARGET LINK_NAME
Input:
# Create a symbolic link named link.txt pointing to file1.txt with verbose output
$ ln -sv file1.txt link.txt
Output:
'link.txt' -> 'file1.txt'
4.6. -b, --backup[=CONTROL]
: Create Backups
- Purpose: Creates a backup of the destination file before overwriting.
- Syntax:
ln -b [OTHER_OPTIONS] TARGET LINK_NAME
Input:
# Create a file named data.txt with content
$ echo "Original" > data.txt
# Create a file named new_data.txt with content
$ echo "New Data" > new_data.txt
# Create or update a symbolic link named data.txt to new_data.txt with backup, overwriting any existing file or link (-f) and creating a backup of the original data.txt if it exists (-b).
$ ln -sfb new_data.txt data.txt
Output:
# List the files to show the backup
$ ls
data.txt data.txt~ new_data.txt
# Display the content of the backup file
$ cat data.txt~
Original
# Display the content of data.txt (now linked to new_data.txt)
$ cat data.txt
New Data
# Display the content of new_data.txt
$ cat new_data.txt
New Data
4.7. -S, --suffix=SUFFIX
: Custom Backup Suffix
- Purpose: Specifies a custom suffix for backup files.
- Syntax:
ln -bS SUFFIX [OTHER_OPTIONS] TARGET LINK_NAME
Input:
# Create a file named settings.conf with content
$ echo "Old data" > settings.conf
# Create a file named new_settings.conf with content
$ echo "New settings" > new_settings.conf
# Create or update a symbolic link named settings.conf to new_settings.conf with custom backup suffix
$ ln -sfbS .bak new_settings.conf settings.conf
Output:
# List the files to show the backup with custom suffix
$ ls
new_settings.conf settings.conf settings.conf.bak
# Display the content of the backup file
$ cat settings.conf.bak
Old data
# Display the content of settings.conf (now linked to new_settings.conf)
$ cat settings.conf
New settings
# Display the content of new_settings.conf
$ cat new_settings.conf
New settings
5. Combining Options
5.1. Common Combinations
ln -sf
: Creates a symbolic link and forces overwrite.# Create or update a symbolic link named app_link to new_version, overwriting if necessary $ ln -sf new_version app_link
ln -sfn
: Creates a symbolic link, forces overwrite, and treatsLINK_NAME
as a file.# Create or update a symbolic link named current_dir_link to new_dir, treating it as a file $ ln -sfn new_dir current_dir_link
ln -iv
: Creates a link interactively with verbose output.# Create a link named link.txt to file.txt with interactive prompt and verbose output $ ln -iv file.txt link.txt
6. Handling Special Cases
6.1. Filenames Starting with Hyphen
- Solution: Use
--
to indicate the end of options or prefix with./
. - Example:
# Create a file named -file.txt (filename starts with hyphen) $ touch -- -file.txt # Create a hard link named -link.txt to -file.txt using -- $ ln -- -file.txt ./-link.txt # List the files to verify $ ls -l -rw-r--r-- 1 user user 0 May 12 20:00 -file.txt -rw-r--r-- 1 user user 0 May 12 20:00 -link.txt
### 6.2. Filenames with Spaces
- **Solution**: Quote or escape spaces.
- **Example**:
```bash
# Create a symbolic link named "link to doc.lnk" pointing to "document one.txt"
$ ln -s "document one.txt" "link to doc.lnk"
6.3. Permissions
- Key Points:
- Write permission is required in the directory to create links.
- Target file permissions do not affect link creation.
- Symbolic link permissions (
lrwxrwxrwx
) are typically ignored; target permissions apply.
- Example:
# Create a file named restricted.txt $ touch restricted.txt # Set read-only permissions on restricted.txt $ chmod 444 restricted.txt # Create a hard link named link.txt to restricted.txt $ ln restricted.txt link.txt # List the files to show permissions $ ls -l -r--r--r-- 1 user user 0 May 12 20:00 restricted.txt -r--r--r-- 1 user user 0 May 12 20:00 link.txt
6.4. Directories
- Key Points:
- Symbolic links can point to directories.
- Hard links to directories are generally prohibited to prevent filesystem loops.
- Example:
# Create a symbolic link named log_link pointing to /var/log $ ln -s /var/log log_link # List the symbolic link $ ls -l lrwxrwxrwx 1 user user 8 May 12 00:00 log_link -> /var/log
7. Frequently Asked Questions (FAQ)
7.1. What is the difference between a hard link and a symbolic link?
- Hard Link: Shares the same inode, cannot cross filesystems, and persists if other links exist.
- Symbolic Link: Points to a path, can cross filesystems, and becomes broken if the target is removed.
7.2. When should I use a hard link vs. a symbolic link?
- Hard Links: For multiple names within the same filesystem where data persistence is needed.
- Symbolic Links: For shortcuts, cross-filesystem links, or directory links.
7.3. How can I identify a symbolic link?
- Use
ls -l
(showsl
and->
) orfile
command.# Create a file named file.txt with content $ echo "Hello" > file.txt # Create a symbolic link named symlink.txt pointing to file.txt $ ln -s file.txt symlink.txt # List the symbolic link to identify it $ ls -l symlink.txt lrwxrwxrwx 1 user user 8 May 12 20:00 symlink.txt -> file.txt # Use file command to identify the type $ file symlink.txt symlink.txt: symbolic link to file.txt
7.4. What happens if I delete a symbolic link’s target?
- The link becomes “broken,” causing access errors.
# Create a file named file.txt with content $ echo "Hello" > file.txt # Create a symbolic link named symlink.txt pointing to file.txt $ ln -s file.txt symlink.txt # List the symbolic link $ ls -l symlink.txt lrwxrwxrwx 1 user user 8 May 12 20:00 symlink.txt -> file.txt # Delete the target file $ rm file.txt # List the symbolic link (often shown in red by ls) $ ls -l symlink.txt lrwxrwxrwx 1 user user 8 May 12 20:00 symlink.txt -> file.txt # Attempt to access the broken symlink $ cat symlink.txt cat: symlink.txt: No such file or directory
7.5. Can I create a hard link to a directory?
- No, most systems prevent this to avoid filesystem issues.
7.6. How do I update a symbolic link?
- Use
ln -sfn NEW_TARGET EXISTING_SYMLINK
.# Update an existing symbolic link to point to a new target $ ln -sfn new_file.txt old_symlink
7.7. Should I use relative or absolute paths for symbolic links?
- Relative Paths: Portable if the link and target move together.
- Absolute Paths: Fixed to a specific location.
# Create a symbolic link with a relative path $ ln -s ../data/file.txt relative_link # Create a symbolic link with an absolute path $ ln -s /data/file.txt absolute_link
8. Conclusion
The ln
command is a cornerstone of Linux file management, offering hard links for robust data access within a filesystem and symbolic links for flexible shortcuts across systems. Its options, such as -s
, -f
, and -n
, provide precise control, making it invaluable for scripting, system administration, and everyday use. By understanding its capabilities and nuances, you can streamline your workflow and manage files effectively.
9. ln Command: Reference Table of Key Options
Option(s) | Description | Example Command | Use Case |
---|---|---|---|
(none) | Create a hard link | ln file.txt hardlink.txt | Multiple names for the same file data |
-s, --symbolic | Create a symbolic link | ln -s /etc/passwd passwd_link | Create shortcuts to files or directories |
-f, --force | Remove existing destination files | ln -sf new.txt link.txt | Update links by overwriting |
-i, --interactive | Prompt before overwriting | ln -i new.txt link.txt | Confirm overwrites |
-n, --no-dereference | Treat LINK_NAME as a file | ln -sfn file.txt link_to_dir | Replace symlinks to directories |
-T, --no-target-directory | Treat LINK_NAME as a file | ln -T file.txt dir | Avoid linking inside directories |
-v, --verbose | Print linked file names | ln -sv file.txt link.txt | Confirm link creation |
-b, --backup[=CONTROL] | Backup destination files | ln -sfb new.txt link.txt | Preserve original files |
-S, --suffix=SUFFIX | Custom backup suffix | ln -sfbS .bak new.txt link.txt | Custom backup naming |
-t, --target-directory=DIR | Specify link directory | ln -s -t links/ file1.txt | Link multiple files to a directory |
-L, --logical | Follow symbolic link targets | ln -L symlink.txt hardlink.txt | Link to the target of a symlink |
-P, --physical | Link to the symlink itself | ln -P symlink.txt hardlink.txt | Create hard link to a symlink |