Links let one file be reached by more than one name. Linux has two kinds: symbolic links (symlinks) and hard links.
Symbolic links
A symlink is a small special file that contains a path to something else. Create one with ln -s, giving the target first and the link name second:
$ echo hello > report.txt
$ ln -s report.txt latest
$ ls -l latest
lrwxrwxrwx 1 sam sam 10 Jan 5 10:12 latest -> report.txt
$ cat latest
helloThe leading l and the arrow show it is a link. The permissions on a Linux symlink are not used; those of the target apply.
If the target is removed or renamed, the link stays but points to nothing. That is a broken or dangling link:
$ rm report.txt
$ cat latest
cat: latest: No such file or directorySymlinks can point to directories and can cross filesystems. A relative target is resolved from the directory holding the link, not from where you are standing. Check this when links are in other directories. readlink latest prints the stored path.
Hard links
A hard link is another directory entry for the same inode. Use ln without -s:
$ echo data > a
$ ln a b
$ ls -li a b
46877 -rw-r--r-- 2 sam sam 5 Jan 5 10:12 a
46877 -rw-r--r-- 2 sam sam 5 Jan 5 10:12 bBoth names share the inode number, and the link count is 2. Neither is the "original". Removing a leaves b fully usable.
Hard links cannot cross filesystems, and you normally cannot make one to a directory. Some systems also restrict hard links to files you do not own.
Removing and replacing
Remove a link with rm latest. This removes the link, not the target. Avoid a trailing slash on a link to a directory.
To repoint an existing link:
$ ln -sfn newtarget latest-f replaces the existing link, and -n stops ln from following a link to a directory and creating the new link inside it.
Try it
Make one symlink and one hard link to the same file. Compare them with ls -li, delete the first name, and see which still works. Practise in the files and links lab.
Check your understanding
Symlinks
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.