How To Create Hard Link In Linux – Using Ln Command Syntax

Hard links in Linux create multiple directory entries pointing to the same file data. If you want to learn how to create hard link in linux, this guide will walk you through every step with clear examples and practical tips. Hard links are a powerful feature for managing files efficiently, and by the end of this article, you will be able to use them confidently in your daily work.

What Is A Hard Link In Linux

A hard link is essentially another name for an existing file on the same filesystem. When you create a hard link, you are not copying the file data. Instead, you are adding a new directory entry that points to the same inode—the data structure that stores file metadata and content. This means the original file and the hard link share the same data blocks.

Unlike symbolic links (soft links), hard links do not reference a path. They directly reference the inode. If you delete the original file, the hard link still works because the data remains accessible through the link. The data is only removed when all hard links to that inode are deleted.

Hard links have some important limitations. They cannot span across different filesystems or partitions. You also cannot create a hard link to a directory (except for the special . and .. entries). And they only work on files, not on special file types like device files or FIFOs.

How To Create Hard Link In Linux

Now let us get straight into the main topic. The command to create a hard link is ln. The basic syntax is:

ln target_file link_name

Here, target_file is the existing file you want to link to, and link_name is the name of the new hard link you want to create. You must specify both arguments. If you only provide one argument, ln will create a link in the current directory with the same name as the target.

Let us look at a simple example. Suppose you have a file called original.txt with some text content. To create a hard link named link_to_original.txt, run:

ln original.txt link_to_original.txt

After running this command, both original.txt and link_to_original.txt point to the same data. You can verify this by checking the inode numbers using the ls -i command. Both files will show the same inode number.

Step-By-Step Guide To Create Hard Links

Follow these steps to create hard links in your Linux system:

  1. Open a terminal window.
  2. Navigate to the directory where your target file is located using the cd command.
  3. Create a test file if you do not have one. For example: echo "Hello, World!" > testfile.txt
  4. Run the ln command with the target file and the desired link name: ln testfile.txt hardlink_test.txt
  5. Verify the link by listing files with inode numbers: ls -li. Both files should have the same inode number.
  6. Check that the link count has increased. Run ls -l and look at the number after the permissions. For a file with one hard link, it shows 1. After creating a hard link, it shows 2.

Creating Hard Links In Different Directories

You can also create hard links that point to files in other directories. The syntax remains the same, but you need to provide the correct paths. For example:

ln /home/user/documents/report.txt /home/user/backups/report_backup.txt

This creates a hard link in the backups directory that points to the same data as the original file in the documents directory. Remember, both files must be on the same filesystem. If you try to create a hard link across different filesystems, you will get an error message like “Invalid cross-device link”.

Checking Hard Link Count

To see how many hard links point to a file, use the ls -l command. The second column in the output shows the link count. For a regular file, the minimum link count is 1 (the file itself). Each additional hard link increases this number by 1.

You can also use the stat command to get detailed information about a file, including the link count. For example:

stat testfile.txt

Look for the line that says “Links:” followed by a number. This shows the total number of hard links pointing to the inode.

Practical Examples Of Hard Links

Hard links are useful in many real-world scenarios. Here are a few common use cases:

  • Backup and versioning: You can create hard links to keep multiple versions of a file without duplicating data. For example, if you have a configuration file, you can create a hard link with a timestamp in the name to preserve a snapshot.
  • File organization: If a file belongs to multiple categories, you can create hard links in different directories. For instance, a photo of a family event can have hard links in both “Vacation” and “Family” folders.
  • System administration: Many system utilities use hard links for efficient file management. For example, the git version control system uses hard links internally to store objects.
  • Sharing data between users: If multiple users need access to the same file, you can create hard links in their home directories. However, be careful with permissions and ownership.

Hard Links Vs Soft Links

It is important to understand the difference between hard links and symbolic links (soft links). Here is a quick comparison:

  • Hard links: Point directly to the inode. They work only on the same filesystem. Deleting the original file does not break the link. They cannot link to directories.
  • Soft links: Point to a file path. They can span across filesystems. Deleting the original file breaks the link (becomes a dangling symlink). They can link to directories.

To create a symbolic link, use the -s option with ln: ln -s target link_name. The output of ls -l shows symbolic links with an arrow (->) pointing to the target.

Common Mistakes And Troubleshooting

When learning how to create hard link in linux, you might encounter some errors. Here are the most common ones and how to fix them:

  • “Invalid cross-device link”: This happens when you try to create a hard link across different filesystems. Use the df command to check which filesystem a file is on. Move the target file to the same filesystem before creating the link.
  • “Operation not permitted”: This error occurs when you try to create a hard link to a directory. Remember, hard links to directories are not allowed (except for the system-managed . and ..). Use symbolic links for directories instead.
  • “No such file or directory”: You mistyped the path or the target file does not exist. Double-check the file name and path.
  • “Permission denied”: You do not have write permission in the target directory. Use sudo or change directory permissions.

How To Delete Hard Links

Deleting a hard link is the same as deleting a regular file. Use the rm command:

rm hardlink_name

This removes the directory entry for that hard link. The file data remains accessible through other hard links. Only when the last hard link is deleted does the system free the disk space. You can check the link count before deleting to see how many links remain.

Advanced Hard Link Techniques

For power users, there are some advanced techniques involving hard links:

  • Using find with hard links: You can use the find command to locate all hard links to a specific inode. First, get the inode number with ls -i, then run: find /path -inum INODE_NUMBER. This shows all files with that inode.
  • Hard links and backup tools: Tools like rsync and cp -l can create hard links instead of copying data. The cp -l command creates hard links to files instead of copying them. This saves disk space and time.
  • Link count and file systems: Some filesystems have a maximum link count per inode. For example, ext4 allows up to 65,000 hard links. If you exceed this limit, you will get an error.

Hard Links In Scripts

You can use hard links in shell scripts to manage files efficiently. For example, a backup script might create hard links to existing files before overwriting them:

#!/bin/bash
# Simple backup script using hard links
cp -l /etc/config.conf /backup/config.conf.backup
cp /etc/config.conf /etc/config.conf.new

This script creates a hard link of the original configuration file in the backup directory, then overwrites the original with a new version. If something goes wrong, you still have the old version through the hard link.

Performance Considerations

Hard links have minimal performance overhead. Creating a hard link is very fast because it only adds a directory entry and increments the link count. There is no data copying involved. However, there are a few things to keep in mind:

  • Disk space: Hard links do not consume additional disk space for the file data. Only the directory entry takes a small amount of space (typically a few bytes).
  • Inode usage: Each hard link uses one inode for the directory entry. Inodes are a finite resource on a filesystem. If you create millions of hard links, you might run out of inodes even if you have free disk space.
  • File system fragmentation: Hard links do not cause fragmentation because they point to the same data blocks. However, if you modify a file through one hard link, the changes are visible through all other hard links (since they share the same data).

Frequently Asked Questions

Can I Create A Hard Link To A Symbolic Link?

Yes, you can create a hard link to a symbolic link file itself (not to the target of the symlink). The hard link will point to the symlink’s inode, not to the original file. This is rarely useful, but it is possible.

What Happens If I Edit A File Through A Hard Link?

Editing a file through any hard link modifies the shared data. All other hard links to the same inode will reflect the changes immediately. This is because they all point to the same data blocks on disk.

How Do I Find All Hard Links To A File?

Use the find command with the -samefile option: find /path -samefile target_file. This shows all files that share the same inode as the target file. Alternatively, use find /path -inum INODE_NUMBER after getting the inode number.

Can I Create A Hard Link To A File In A Different Filesystem?

No, hard links cannot cross filesystem boundaries. If you need to link across filesystems, use a symbolic link instead. The ln command will give you an “Invalid cross-device link” error if you try.

Is There A Limit To The Number Of Hard Links I Can Create?

Yes, each filesystem has a maximum link count per inode. For ext4, the limit is 65,000. For other filesystems like XFS, the limit is much higher (around 2^32). Check your filesystem documentation for specific limits.

Summary

Learning how to create hard link in linux is a valuable skill for efficient file management. The ln command is simple to use, but understanding the underlying concepts—inodes, link counts, and filesystem limitations—helps you avoid common mistakes. Hard links save disk space by avoiding data duplication, and they provide a robust way to organize files across multiple directories.

Remember these key points:

  • Use ln target link_name to create a hard link.
  • Hard links must be on the same filesystem.
  • They cannot link to directories.
  • Deleting one hard link does not affect others.
  • Use ls -li to verify inode numbers and link counts.

Practice with simple examples in a test directory. Once you are comfortable, you can start using hard links in your daily workflow for backups, file organization, and system administration tasks. The more you use them, the more you will appreciate their simplicity and power.