Intermediate · 10 min · practise every command in the built-in terminal

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 in sites-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 linkHard link
Storesa pathnothing — it is the file
Target deletedbrokenthe file stays
For foldersyesno
Across disksyesno

💡 Day to day you'll use symbolic links; hard links are what backup tools use to keep many snapshots without copying every file again.

Practice tasks

  1. Make a symbolic link ~/system-logs that points to /var/log
  2. Show where ~/system-logs points
  3. Make list.txt and a hard link to it called list-copy.txt, then show that both have the same inode
  4. Delete list.txt and show that list-copy.txt still has the text
  5. Make ~/site/current point to ~/site/v1, then switch it to ~/site/v2

Commands in this lesson

Files & Directories