link - Linux
Overview
The link
command in Linux is used to create a hard link between two files. A hard link is a directory entry that associates a name with a file on a file system. All hard links to a file share the same data blocks and have the same file permissions and ownership. This command is useful for organizing files, saving space, and ensuring multiple access points for critical data without duplication.
Syntax
The usage syntax for the link
command is straightforward:
link SOURCE TARGET
- SOURCE: The path to an existing file.
- TARGET: The path where the new hard link will be created.
Parameters:
- SOURCE and TARGET are both required and must specify existing and valid paths where the user has appropriate permissions.
Options/Flags
The link
command does not have any options or flags. It performs one function only, and any additional parameters passed will result in an error.
Examples
1. Basic Usage: Create a hard link to a file:
link file1.txt link1.txt
This command creates a hard link link1.txt
pointing to file1.txt
.
2. Verifying Hard Links: To confirm that the link was created:
ls -li file1.txt link1.txt
The output would show both files having the same inode number, confirming they are hard linked.
3. Error Scenario: Attempting to create a hard link across file systems:
link /path/to/sourcefile.txt /mnt/other_fs/hardlink.txt
This command may fail if /path/to/sourcefile.txt
and /mnt/other_fs/hardlink.txt
are on different file systems.
Common Issues
1. Cross-Filesystem Limitation:
Hard links cannot be created across different file systems. A common error message for this issue is “Invalid cross-device link”. To resolve, ensure that both the source and target paths are on the same file system.
2. Permission Errors:
If you do not have write permissions in the directory where you’re attempting to create the hard link, you will encounter a permission denied error. Ensure appropriate permissions or use sudo
if suitable.
Integration
The link
command can be combined with other commands for file management tasks. For example, to find duplicate files and replace them with hard links to save space:
fdupes -r /path/to/files | xargs link commonfile.txt
Here, fdupes
searches for duplicate files, and link
creates hard links to unify duplicates, conserving disk space.
Related Commands
ln
: More commonly used thanlink
for creating both hard and symbolic links. Offers more features including symbolic link creation and options like-s
for symbolic links and-f
to force link creation.unlink
: Command to remove a single hard link (i.e., a file name in a directory).
For more detailed documentation on file system commands, consult the man pages (man link
) or visit online resources dedicated to Linux file management.