The ln Commands You Will Use Most
ln -s /var/www/releases/v2 /var/www/current
ln -sfn /var/www/releases/v3 /var/www/current
readlink -f /var/www/current
ls -l /var/www/current
The order is target first, link name second, the same order as cp. The first command creates /var/www/current pointing to the release folder. The second points the existing link to a new release. The last two show where a link points.
Create a Link
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
When the second argument is an existing folder, the link is created inside it with the target's name. The example above is how sites are enabled with the Nginx package on Debian and Ubuntu. After it, test and reload: sudo nginx -t, then sudo systemctl reload nginx. The target does not have to exist when you create the link; ln does not check, so a typo gives you a broken link without an error.
Symbolic Links and Hard Links
| Symbolic link | Hard link | |
|---|---|---|
| Command | ln -s | ln |
| Points to | A path | The file data itself |
| Folders | Yes | No |
| Other disks | Yes | No, same filesystem only |
| Target deleted | Link breaks | Data stays |
A hard link is a second name for the same file: both names share one inode, which ls -i shows. The data is removed only when the last name is deleted. In daily server work, symbolic links are the usual choice.
Update an Existing Link
ln does not replace an existing link by default; it reports that the file exists. -f removes the old link first. When the old link points to a folder, also add -n, or ln follows the link and creates the new link inside the target folder:
ln -sfn /var/www/releases/v3 /var/www/current
Check the result with ls -l: the line shows current -> /var/www/releases/v3.
Read Where a Link Points
readlink current: prints the target exactly as it was written.readlink -f current: prints the full final path, following every link on the way.ls -l: shows links with anlin the first column and the target after an arrow; the columns are explained in the ls command guide.
Relative or Absolute Targets
An absolute target, such as /var/www/releases/v3, works wherever the link is. A relative target is resolved from the folder that contains the link, not from the folder you were in when you created it. That surprises many people:
cd /var/www
ln -s releases/v3 current
ln -sr /var/www/releases/v3 /var/www/current2
Relative links keep working when the whole tree is moved or copied to another path. -r works out the relative path for you.
Find Broken Links
find /var/www -xtype l
With GNU find, -xtype l lists links whose target no longer exists. Check each one before you delete it; more search options are in the find command guide.
Remove a Link
rm /var/www/current
unlink /var/www/current
Both remove only the link, never the target. Do not add a trailing slash to a link that points to a folder, and never use rm -r on it; see how to remove a directory in Linux for deleting real folders.