Symlinks vs Hard Links

Updated: 2020-06-29
  • hard links can only link to files, must be on the same partition (you cannot hard link across file systems or volumes), if the original is deleted, the link will still work since it links to the underlying data (which means you need to delete all hard links to delete a file).
  • symlinks can point to both files and directories, no partition limits, if the original is deleted, the link will not work
  • hard links always refer to an existing file, symlinks may contain an arbitrary path.
  • chown will affect all hard links, but will not change symlinks

Example:

$ echo a > a.txt
$ echo b > b.txt
$ cat a.txt
a
$ cat b.txt
b

Create links:

$ ln a.txt a-hard-link    # create a hard link to a.txt
$ ln -s b.txt b-symlink   # create a symlink to b.txt
$ ls -l
a-hard-link               # hard link will not show `->`
a.txt
b-symlink -> b.txt        # symlink will show `->` and its original file
b.txt

Rename a.txt, the hard link would still work

$ mv a.txt a2.txt
$ cat a-hard-link
a

Rename b.txt, the symlink will break

$ mv b.txt b2.txt
$ cat b-symlink
cat: b-symlink: No such file or directory