A symbolic link (or link) is a small file that points to another path. When a program opens the link, it gets the item that the link points to, the target.
Make a link: ln -s
ln -s TARGET LINK makes the link LINK, which points to TARGET:
learner@tidepool:~/shop$ ln -s menus/summer.txt menu.txt
learner@tidepool:~/shop$ ls -l
lrwxrwxrwx 1 learner learner 16 Oct 12 09:14 menu.txt -> menus/summer.txt
drwxr-xr-x 2 learner learner 4096 Oct 12 09:14 menus
learner@tidepool:~/shop$ cat menu.txt
ice teaIn ls -l, a link has the type l, and the arrow -> shows its target.
A relative target is read from the directory of the link, not from your current directory.
Why links are useful
A link gives one fixed name to something that changes. The shop keeps two menus. Programs always read menu.txt. To change the menu, change the link. Do not copy files.
- app
- releases
- v1
- v2
- current← a link to releases/v2
Programs often use this for their versions, or releases: one directory for each release, and a link current to the one that runs.
A broken link
If you delete or move the target, the link stays and points to nothing. This is a broken link:
learner@tidepool:~/shop$ cat menu.txt
cat: menu.txt: No such file or directoryls -l still lists the link and its old target.
Change where a link points
ln -s refuses a name that exists: File exists. Add flags:
| Line | Use for |
|---|---|
ln -sf NEW LINK | A link to a file |
ln -sfn NEW LINK | A link to a directory |
-f replaces the old link. With a link to a directory, also add -n. Without -n, ln goes into the directory and makes the new link there.
rm LINK deletes only the link, never the target.