ln — Links
A link is one more name for a file. Linux has two kinds: symbolic links (shortcuts) and hard links.
Symbolic links
ln -s TARGET NAME
ln -s /var/log ~/system-logs # ~/system-logs now leads to /var/log
ls -l ~/system-logs # lrwxrwxrwx ... system-logs -> /var/log
ls ~/system-logs # what's in /var/log
readlink ~/system-logs # where the link points
The l at the start of ls -l and the -> give a link away. A symbolic link only stores a path — like a shortcut on a desktop.
cd into a link and pwd shows the way you came; pwd -P shows where you really are:
cd ~/system-logs
pwd # /home/student/system-logs
pwd -P # /var/log
cd
Where they are used every day:
- a short name for a long path (
~/system-logs→/var/log) - a "current" version:
current -> releases/v2— switching versions is one command - turning a configuration on: nginx's
sites-enabled/holds links to files insites-available/
Broken links
If the target goes away, the link stays — and leads nowhere:
echo hello > note.txt
ln -s note.txt shortcut
rm note.txt
cat shortcut # No such file or directory
ls -l shortcut # still there, still -> note.txt
find ~ -xtype l # every broken link under your home
Pointing a link somewhere else
mkdir -p ~/site/v1 ~/site/v2
ln -s v1 ~/site/current # a relative target: v1 next to the link
ln -sfn v2 ~/site/current # now it leads to v2
ls -l ~/site
-f replaces the old link. -n matters as much: without it, ln follows current into the folder it leads to and makes a new link inside v1.
Hard links
Without -s, ln makes a hard link: a second name for the very same file.
echo "shopping list" > list.txt
ln list.txt list-copy.txt
ls -li list.txt list-copy.txt # the same inode number, link count 2
echo "milk" >> list-copy.txt
cat list.txt # milk is here too — it is one file
rm list.txt
cat list-copy.txt # still there
The first column of ls -li is the inode — the file itself. A name is just a way to it, and the file is deleted when its last name goes.
| Symbolic link | Hard link | |
|---|---|---|
| Stores | a path | nothing — it is the file |
| Target deleted | broken | the file stays |
| For folders | yes | no |
| Across disks | yes | no |
💡 Day to day you'll use symbolic links; hard links are what backup tools use to keep many snapshots without copying every file again.