Linux - soft and hard links in Unix/Linux

What are Links in Linux?

In Linux, a link is a way to refer to a file from another location in the file system, kind of like a shortcut or pointer.

There are two types:

  1. Hard Link

  2. Soft Link (Symbolic Link)


1. Hard Link

What is it?

A hard link is an exact duplicate of a file.
It points to the actual data on the disk, not just the file name.

Key Points:

  • Both the original and hard link share the same data (inode).

  • If you delete the original file, the data still exists through the hard link.

  • Hard links only work with files, not directories (unless you're root).

  • Cannot link across file systems.

Create a hard link:

ln original.txt hardlink.txt

Example:

echo "hello" > original.txt
ln original.txt copy.txt
cat copy.txt      # Output: hello

Even if you delete original.txt, copy.txt still contains the same data.


2. Soft Link (Symbolic Link)

What is it?

A soft link is like a shortcut or alias.
It points to the name/path of the file, not the actual data.

Key Points:

  • If the original file is deleted, the soft link becomes broken (points to nothing).

  • Can be used for files or directories.

  • Can link across file systems.

  • Identified with l in ls -l.

Create a soft link:

ln -s original.txt shortcut.txt

Example:

echo "hello" > original.txt
ln -s original.txt shortcut.txt
cat shortcut.txt   # Output: hello

If you now delete original.txt, the soft link (shortcut.txt) is broken.


Comparing Hard vs Soft Links

Feature Hard Link Soft Link (Symbolic)
Points to Actual data (inode) File name/path
Works across file systems No Yes
Works for directories No (usually) Yes
Broken if original is deleted No Yes
Command to create ln file linkname ln -s file linkname

Check Links Using ls -li

ls -li original.txt hardlink.txt
  • If both files have the same inode number, they are hard-linked.

  • Soft links will have a different inode and show the target path with an arrow (->).

 

Let me know if you want a hands-on exercise, diagram, or cheat sheet!