ln: create symbolic and hard links
ln creates links: extra names for files. Symbolic links point to a path and are used everywhere, from switching software versions to /etc/systemd configuration.
ln -s target linkname # symbolic link
ln target linkname # hard link
Symbolic links
A symbolic (soft) link is a small file containing a path. Opening the link opens whatever the path points to.
ln -s /opt/app-2.4 /opt/app # /opt/app now leads to /opt/app-2.4
ls -l /opt/app # lrwxrwxrwx ... /opt/app -> /opt/app-2.4
readlink /opt/app # print the target
readlink -f /opt/app # the final target, all links resolved
ln -sfn /opt/app-2.5 /opt/app # point the link at a new version
The order is the same as for cp: what exists first, the new name second. Relative targets are relative to the link's own directory, not to where you are: ln -s ../shared/config.yml app/config.yml.
Hard links
A hard link is a second directory entry for the same file (the same inode). Both names are equal: the data is only removed when the last name is deleted.
ln data.csv data-copy.csv
ls -li data.csv data-copy.csv # same inode number, link count 2
| Symbolic link | Hard link | |
|---|---|---|
| Can point to directories | Yes | No |
| Can cross file systems | Yes | No |
| If the original is deleted | The link breaks | The data stays |
| Shows where it points | Yes (ls -l) | No, both names are equal |
Options
| Option | Meaning |
|---|---|
-s | Symbolic link |
-f | Replace an existing link name |
-n | Treat an existing link to a directory as a file (needed with -f to replace it) |
-r | Make the target relative to the link location (GNU) |
-v | Show what is linked |
Find broken links
find /etc -xtype l # GNU find: symbolic links whose target is missing
find . -type l ! -exec test -e {} \; -print # portable version