Skip to content

Shortcuts with ln -s: symbolic links

IntermediateLesson 18 of 666 min

Make shortcuts with ln -s, read them in ls -l, repoint a link with ln -sfn and avoid the link-inside-a-folder trap, in a terminal in your browser.

A symbolic link (a symlink) is a small file that points to another path, like a shortcut on a desktop. Open the link and you get whatever it points to.

People use them all the time:

  • a current link that points to the latest release, so switching versions is one command;
  • a short name in your home folder for a folder buried deep somewhere else;
  • settings files kept in one folder and linked to where programs look for them.

Making one

ln -s TARGET NAME: the thing that exists comes first and the new name second, the same order as cp.

ln -s releases/v2/index.html latest.html
ls -l

ls -l shows a link with an l at the start and an arrow to its target. readlink current prints just the target.

Two things that catch people out

  1. A relative target starts from where the link lives, not from where you are. ln -s releases/v2 current works in your home folder because releases/v2 is next to current.
  2. A link to a folder acts like the folder. If current points to a folder and you run ln -s releases/v2 current, ln puts a new link inside that folder. To replace the link itself, add -f (force) and -n (treat the link as a file):
ln -sfn releases/v2 current

Deleting a link with rm current removes only the link; the target stays. Move or delete the target and the link breaks: it still points to the old path, and cat says "No such file or directory".

Without -s, ln makes a hard link: a second name for the same file. You'll meet those less often.

Your turn

Version 2 of the site is ready. Make current point to releases/v2 instead of releases/v1. Then add a shortcut called logs in your home folder that points to /var/log.

Next