Linux ln command
The ln
command in Linux is used to create links between files or directories. Links are pointers that reference other files or directories. There are two types of links: hard links and symbolic (soft) links.
Hard Links vs. Symbolic Links
- Hard Link: A hard link is a direct reference to the file’s data on disk, meaning it’s essentially another name for the same file. Hard links share the same inode as the original file and don’t break if the original file is moved or renamed.
- Symbolic (Soft) Link: A symbolic link is more like a shortcut pointing to the file’s path. If the original file is deleted, the symbolic link breaks and becomes a “dangling link.”
Basic Syntax
Common Options
-s
: Creates a symbolic (soft) link.-v
: Provides verbose output, showing each link created.
Examples with Output
Example 1: Creating a Hard Link
A hard link is created without any special options.
Command:
Output:
This means that hardlink_to_file1.txt
is now a hard link to file1.txt
. Any changes made to either file affect both, as they reference the same data on disk.
Example 2: Creating a Symbolic Link
To create a symbolic (soft) link, use the -s
option.
Command:
Output:
This output shows that symlink_to_file1.txt
is now a symbolic link to file1.txt
. Deleting file1.txt
will make symlink_to_file1.txt
invalid.
Example 3: Symbolic Link to a Directory
You can create symbolic links to directories in the same way.
Command:
Output:
This means DocsLink
is a symbolic link to the Documents
directory. Accessing DocsLink
will take you to /home/user/Documents
.
Example 4: Overwriting an Existing Link
If a symbolic link already exists with the same name, you can use -f
to forcefully overwrite it.
Command:
Output:
Now, symlink_to_file1.txt
points to new_file.txt
instead of the original file.
Example 5: Creating a Link in Another Directory
You can create a link in another directory by specifying the full path.
Command:
Output:
This command creates a symbolic link called file_link
in /home/user/Links
that points to file1.txt
in the current directory.
The ln
command is powerful for organizing files, creating shortcuts, and managing references across directories.