ln


ln (create links)

The ln command creates links between files. By default, ln creates hard links. A hard link is a direct reference to the same data on the disk (inode), essentially creating another name for the same file.


Example 1: Create a hard link to a file

# Create a hard link named 'hlink_main' that points to the file 'main.c'
ln main.c hlink_main

Explanation: This creates hlink_main, which is another name for the data contained in main.c. Both names point to the same inode. If you delete main.c, the file content will still be accessible through hlink_main.


Example 2: See inode numbers to verify a hard link

# List the files with their inode numbers to show they are the same
ls -i main.c hlink_main

Explanation: The -i option for ls displays the inode number of each file. Running this after creating a hard link will show that both the original filename and the link name have the identical inode number, proving they point to the same data.


Example 3: Create a hard link in a different directory

# Create a hard link in the '../backup' directory that points to 'config.ini'
ln config.ini ../backup/

Explanation: This command creates a hard link named config.ini inside the ../backup directory. Both config.ini in the current directory and ../backup/config.ini now point to the exact same file data.


Example 4: The effect of editing a hard-linked file

# Edit the original file
echo "New content" >> main.c
# Display the content of the link; it will be updated
cat hlink_main

Explanation: Since a hard link is not a copy but another name for the same data, any changes made through one of the names are instantly reflected when accessing the file through any other name.


Example 5: Limitation - Hard linking a directory (will fail)

# Attempt to create a hard link to a directory, which is not allowed for users
ln my_dir my_dir_link

Explanation: For historical and filesystem consistency reasons, most Unix-like systems, including RHEL, do not permit users to create hard links to directories. This command will result in an error like ln: my_dir: hard link not allowed for directory.


Example 6: Limitation - Hard linking across filesystems (will fail)

# Attempt to create a hard link from a file on one filesystem to another
ln /home/user/data.txt /mnt/usb/data_link.txt

Explanation: Hard links operate by pointing to an inode within a single filesystem. Therefore, you cannot create a hard link that spans across different partitions or mounted filesystems. This command will fail with an "Invalid cross-device link" error.


Example 7: Deleting a hard link

# Remove one of the hard links to the file
rm main.c
# The data is still accessible through the other link
cat hlink_main

Explanation: Removing one hard link does not delete the file's data as long as other hard links exist. The file's contents are only removed from the disk when the link count (the number of hard links pointing to the inode) drops to zero.