Skip to content

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

Reference a file by path (like a Windows shortcut).

ln -s /path/to/original.txt linkname.txt
- if original is deleted, link becomes broken. - Can point to directories. - Can cross filesystems.

Force create link even if linkname.txt exists.

ln -sf /new/source linkname.txt

Create a link relative to the link location (good for portable folders).

ln -sr ../source/file.txt link.txt

Reference the same physical data (inode) on disk.

ln original.txt linkname.txt
- No -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).


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
(Without -n, if /var/www/current is a symlink to a dir, ln might create the new link INSIDE that dir).


Troubleshooting

Cross-device link? Hard links cannot look across partitions (e.g., / to /home if they are separate). use -s.

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 symlink to see where it points.