What is a symbolic link
- A symbolic link (symlink) is a shortcut that points to a file or folder. It is not a copy.
- You create it with
ln -s. - You remove it with
unlinkorrm. - Deleting a symlink removes only the shortcut, not the original.
If the original is deleted or moved, the symlink breaks (it is "dangling").
Create a symbolic link
ln -s target link_name
targetis the file or folder that already exists.link_nameis the new shortcut.
Example, link a folder:
ln -s /media/music music
Example, link a file to another location:
ln -s /home/user/Documents/original.pdf ~/Desktop/original-link.pdf
Steps:
- Open the terminal.
- Run
ln -s. - Give the full path of the original file or folder first.
- Give the name (and location) of the new link second.
Use full (absolute) paths for the target, or the link may point to the wrong place when you move it.
Check a link
ls -l music
The output starts with l and shows an arrow:
lrwxrwxrwx 1 user user 12 Jan 10 10:00 music -> /media/music
Find broken links in a folder:
find . -xtype l
Remove a symbolic link
With unlink
unlink music
With rm
rm music
Warning: Do not add a trailing slash when you remove a link to a folder.
rm -r music/ can act on the contents of the target folder. Use rm music or unlink music.Replace an existing link
ln -sfn /new/target link_name
-f overwrites an existing link and -n treats a link to a folder as a normal file.
Symbolic and hard links
| Symbolic link | Hard link | |
|---|---|---|
| Command | ln -s | ln |
| Points to | A path | The same data on disk |
| Works for folders | Yes | No |
| Across file systems | Yes | No |
| If the original is deleted | The link breaks | The data stays |
Common uses
- Enable an Nginx site:
ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/. - Keep several versions of software and point
currentto the active one. - Put a short path for a deep folder.
Quick recap
ln -s target linkcreates it,unlink linkremoves it.