ln Command Cheat Sheet
The ln command creates links between files. Links allow a file to be accessible from multiple locations in the directory hierarchy.
Synopsis
ln [OPTION]... [-T] TARGET LINK_NAME
ln [OPTION]... TARGET
Symbolic (Soft) Links
Reference a file by path (like a Windows shortcut).
Create a Symlink
ln -s /path/to/original.txt linkname.txt
Overwrite Symlink (-f)
Force create link even if linkname.txt exists.
ln -sf /new/source linkname.txt
Relative Symlinks (-r)
Create a link relative to the link location (good for portable folders).
ln -sr ../source/file.txt link.txt
Hard Links
Reference the same physical data (inode) on disk.
Create a Hard Link
ln original.txt linkname.txt
-s flag.
- Both files must exist on the same filesystem.
- Deleting original does NOT delete data; data persists until all hard links are gone.
- Cannot link directories (usually).
Managing Links
Backup Existing Destination (-b)
If the target link name usually exists, rename it (append ~) instead of overwriting.
ln -s -b config.new config
No Dereference (-n)
Treat destination that is a symlink to a directory as a file. Critical when changing where a symlink points.
ln -sfn /new/deploy /var/www/current
-n, if /var/www/current is a symlink to a dir, ln might create the new link INSIDE that dir).
Troubleshooting
"ln: failed to create hard link"
Cross-device link?
Hard links cannot look across partitions (e.g., / to /home if they are separate). use -s.
"ln: failed to create symbolic link '...': File exists"
Use -f to force overwrite.
Notes
- Permissions: Valid permissions are determined by the target file, not the symlink itself (which usually has 777).
- readlink: Use
readlink_f symlinkto see where it points.