Part 5 of 7 · 2 min read
Symbolic links
Think of a note on a door that says "Moved to room 12". The note is not the room. If room 12 is closed, the note still hangs there and leads nowhere. The analogy stops in one place: a person can see that a note is out of date, and the OS only learns it when the lookup fails.
In plain words: A symbolic link (symlink) is a file of its own, with its own inode, whose content is a path. When the OS walks a path and meets a symlink, it reads the stored path and continues from there. The link does not change the link count of its target. It can point to a directory, to a file on another file system, or to a path that does not exist, which is called a dangling link.
A worked example. In the output of section 3, soft.txt has its own inode (13), a link count of 1 and a size of 5 bytes, which is the length of the text a.txt. A stat follows the link and reports the target (inode 12). An lstat reports the link itself. After a.txt was removed, the target soft.txt still pointed to the name a.txt, and stat failed because no such name existed any more. The link had become dangling.
The key lines. The size of a symlink is the length of its path, so a link to ../shared/data/report.txt has a size of 25 bytes. The table sums up the differences.
| Question | Hard link | Symbolic link |
|---|---|---|
| What is it? | Another name for the same inode | A separate file that holds a path |
| Own inode? | No | Yes |
| Can cross file systems? | No | Yes |
| Can point to a directory? | Usually not | Yes |
| After the target is removed | Data stays while a name remains | Link dangles |
| Raises the target's link count? | Yes | No |
Symbolic link
A symbolic link is a special file whose content is a path name. The OS substitutes that path when it resolves the link, so the link can name any path, even one that does not exist. The link and its target have separate inodes.
Example: soft.txt holds the path a.txt, which is 5 bytes.
Common mistake
A relative symlink is read from the directory that holds the link, not from the directory of the program that uses it. A link ../x inside /data/a points to /data/x, whatever the current directory is.
Check yourself:
1. What is stored in a symlink?
2. Which of stat and lstat follows a symlink?
3. What is a dangling link, and when does one appear?