Shortcuts with ln -s: symbolic links
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
currentlink 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.htmlls -lls -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
- A relative target starts from where the link lives, not from where you are.
ln -s releases/v2 currentworks in your home folder becausereleases/v2is next tocurrent. - A link to a folder acts like the folder. If
currentpoints to a folder and you runln -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 currentDeleting 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.
Your task
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.
- current points to releases/v2 (not done yet)
- logs is a link to /var/log (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
ln -s- Make a symbolic link instead of a hard link More on ln
ln -sfn- Make a symbolic link instead of a hard link; replace a file that already has the link’s name; treat an existing link to a folder as a file (use with -f to replace it) More on ln
readlink- Print where a symbolic link points
Every everyday command on one page: the Linux commands cheat sheet.