Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Symbolic Links vs Hard Links: ln -s, Inodes, stat, and readlink

One inode with two names versus a file containing a path. Link counts, argument order, the -n flag that decides where a link lands, broken links, and the symlink attacks that follow from careless resolution.

~6 min readLinux
#Linux#File System#CLI
3D illustration of inode cubes shared by two directory names beside a symbolic link chip pointing at a file

Quick Summary

A hard link is a second name for the same inode. Both names are equal, there is no original, and the file's data disappears only when the last link is removed — which is why link count in ls -l matters. A symbolic link is a small file of its own whose content is a path; resolving it costs an extra lookup, works across filesystems, can point at directories, and can dangle when its target is deleted or moved.

The practical differences follow from that design. Hard links cannot cross a filesystem boundary and cannot normally be created for directories, because a directory's .. entry must have one unambiguous parent. Symlinks can point anywhere, including to files that do not exist yet, and every program that opens them has to decide whether to follow the final component. ln -s TARGET NAME puts the target first, which is the reverse of cp and the source of the "my link points at nothing" mistake.

stat, readlink, and realpath are how you see which case you are in: stat -c '%i %h %F' shows the inode number, link count, and file type; readlink -f canonicalizes a chain into an absolute path; realpath --relative-to computes a portable relative target. This guide covers link creation, resolution order, hard-link counts, broken and looping links, archive and container behaviour, and the security consequences of following a link you did not create.

Basic Syntax & Core Signatures

bash
# Symlink: target first, then the name of the link to create ln -s /srv/app/current/config.yml ./config.yml ln -s ../shared/data ./data # relative target, resolved from the link's dir # Replace an existing link (and only a link) atomically-ish ln -sfn /srv/app/release-2 ./current # -n: do not dereference current/ as a directory # Hard link: same inode, same filesystem ln report.txt report-copy.txt # Inspect ls -li report.txt report-copy.txt # same inode number, link count 2 stat -c '%i %h %F %n' report.txt report-copy.txt stat -c '%i %h %F %N' ./current ./config.yml readlink ./config.yml # prints the stored target, one level only readlink -f ./config.yml # canonical absolute path through all links readlink -e ./config.yml # same, but empty output + non-zero if broken readlink -m ./a/b/c # canonicalize even if components are missing realpath --relative-to=/srv/app ./current/config.yml # Find broken links and links in general find . -xtype l # broken symlinks (target type differs) find . -type l -printf '%p -> %l\n' # every link with its target find . -samefile report.txt # every name sharing the inode # Ownership and permissions chown -h deploy:deploy ./config.yml # change the link, not the target chmod 600 ./config.yml # follows the link; changes the target

Resolution rules worth memorizing:

text
ln -s TARGET LINKNAME # create a link called LINKNAME pointing at TARGET cp TARGET LINKNAME # copies TARGET's content to LINKNAME (opposite order) ln -s file link -> link contains "file" (relative to link's directory) ln -s /tmp/file link -> link contains "/tmp/file" (absolute) rm link removes the link; rm -r link/ follows into the target directory cp -a preserves links as links; cp -L copies the data (dereferences) cp -P copies the link itself (GNU: -d = --no-dereference --preserve=links)

Key Comparison Table

AspectHard linkSymbolic link
Stored asAnother directory entry for one inodeA new inode whose data is a path string
Crosses filesystemsNo (same device only)Yes
Can point to a directoryNo (root-only exceptions, discouraged)Yes
Survives deleting the "original" nameYes, data stays while any link existsNo, becomes broken
Relative to its own locationN/AYes — resolved from the link's directory
Broken target possibleNoYes
ls -l showsSame size, link count > 1l type and name -> target
Inode numberIdentical to the targetDifferent from the target
PermissionsShared with the inodeIgnored (mode 777 on Linux, not used)
Space costOne directory entryOne inode plus the target string
Delete behaviourData freed when nlink reaches 0Target untouched; link remains, broken
Typical useDeduplicated snapshots (rsync --link-dest), build cachescurrent pointers, version switching, config indirection
CommandWhat it reports
stat -c '%h' fHard-link count of the inode
stat -L -c '%F' fType of the resolved target
readlink fRaw stored target of a symlink
readlink -f fAbsolute, fully resolved path (empty if a component is missing)
readlink -e fSame but fails silently on missing components
realpath fCanonical path, similar to readlink -f
namei -l pathEvery component with its permissions, resolving each link
find -L . -type fTraverse symlinks as real directories

Practical Edge Cases & Deep Dives

bash
$ echo hello > report.txt $ ln report.txt copy.txt $ ls -li report.txt copy.txt 1311482 -rw-r--r-- 2 user user 6 Nov 15 07:10 copy.txt 1311482 -rw-r--r-- 2 user user 6 Nov 15 07:10 report.txt $ rm report.txt $ cat copy.txt # hello — the data was never in the name $ stat -c '%h' copy.txt # 1

The count of 2 is the kernel's guarantee that the last name to be removed is the one that frees the blocks. Editing through either name edits the single shared inode, so a hard link is not a backup: sed -i on one name may replace the inode entirely (GNU sed writes a temp file and renames), leaving the other name pointing at the old content, which surprises people in both directions.

2. ln -sf into a directory, and the -n flag

bash
$ ls -ld current drwxr-xr-x 2 deploy deploy 4096 ... current # a real directory now $ ln -sf /srv/app/release-2 current $ ls -ld current drwxr-xr-x ... current/ # unchanged: the link went INSIDE it $ ls -l current/release-2 # created /srv/app/release-2 inside current/

Without -n/--no-dereference, ln follows an existing directory and creates the link inside it. The fix is ln -sfn TARGET NAME, and the fully safe version replaces via rename so no window exists where current is missing:

bash
ln -sfn /srv/app/release-2 current.new && mv -T current.new current

mv -T treats the destination as a file, so the rename replaces the directory entry atomically — the standard deploy pattern for current -> release-N.

3. Relative versus absolute targets, and why relative wins in deployments

bash
# Absolute: breaks when the tree is mounted elsewhere, as a chroot or in a container ln -s /srv/app/releases/7 ./current # Relative: keeps working from the link's own directory ln -s releases/7 ./current # ./current -> releases/7

A link's relative target is interpreted from the link's directory, not from the current working directory, so ln -s ../data link inside /srv/app/x points at /srv/app/data regardless of where you run it. Absolute targets are correct for system paths (/usr/bin/python3 -> python3.11, where the directory is fixed) and fragile for anything that gets copied — a relative link survives rsync/tar into a container or a different mount point. realpath --relative-to generates the relative form without arithmetic:

bash
realpath --relative-to=/srv/app /srv/app/releases/7 # releases/7
bash
$ ln -s missing.txt dangling $ cat dangling cat: dangling: No such file or directory $ stat dangling # succeeds: the LINK exists $ stat -L dangling # fails: the target does not $ find . -xtype l # lists dangling $ ln -s loop loop # self-referential $ cat loop cat: loop: Too many levels of symbolic links # ELOOP

Tools differ by default: ls -l shows links as links, ls -L follows them, tar stores links as links unless -h/--dereference is given, and rsync -a preserves them while rsync -aL copies the data. find -type l finds the link, find -L -type f finds the target — the -xtype test is the one that compares against the target type, which is how you find links that point at the wrong kind of thing. A restore that used -h turns a current -> releases/7 pointer into a full copy, silently doubling disk usage and breaking the next deploy.

A symlink in a directory another user can write to is an attack primitive: ln -s /etc/shadow /tmp/upload turns a careless open("/tmp/upload", O_WRONLY|O_CREAT) into a write to a protected file. The kernel services that matter use O_NOFOLLOW on the final component, openat with directory file descriptors, sticky-bit directories (/tmp with 1777), and fs.protected_symlinks=1 (the systemd default), which blocks following a link in a sticky world-writable directory when the link's owner and the directory's owner differ.

Application-level rules that hold regardless of sysctl settings: never chmod/chown a path you did not create without checking lstat, write through a temp file and rename inside the final directory, and treat realpath output as the only path worth logging. For archive extraction, tar --no-overwrite-dir and extracting as a non-root user are the cheap mitigations against the ../ and absolute-link tricks in malicious archives.

bash
$ chmod 600 link # changes the TARGET's mode, not the link's $ chmod -h 600 link # GNU coreutils: affects the link itself (Linux ignores) $ chown -h deploy link # changes the link's owner only $ chown deploy link # changes the target's owner $ rm link # removes the link, target intact $ rm -r link/ # trailing slash: operates on the target directory $ unlink link # same as rm, no directory check

The trailing slash on rm -r link/ is the dangerous one, because the kernel resolves the link before the final component. find . -type l -delete is the precise way to remove a batch of links without touching what they point at.

Common Runtime & Configuration Mistakes

SymptomCauseFix
ln: failed to create hard link: Invalid cross-device linkTarget and link on different filesystemsUse a symlink, or link within one filesystem
ln: failed to create symbolic link 'x': File existsName already existsln -sfn TARGET LINK (add -n for directories)
New link appears inside an existing directory-n missing and the name is a directoryln -sfn
Link points at nothingArguments reversed (ln -s link target)ln -s TARGET LINK, verify with readlink
Relative link breaks after a moveRelative target resolved from the old directoryAbsolute target, or rebuild with realpath --relative-to
cp -r copied data instead of the linkcp dereferences by defaultcp -a / cp -P / cp -d
Archive restore duplicated datatar -h or rsync -L dereferenced linksPreserve links; dereference only deliberately
chmod changed the wrong filechmod follows linkschown -h, lstat before acting
rm -rf dir/ deleted the target's contentsTrailing slash forces resolutionrm dir (no slash) for links
Too many levels of symbolic linksLoop in the chainnamei -l, readlink -f to find the cycle
Backup tool reported a file but restore is emptyDangling link stored and restoredCheck with find -xtype l before and after
Link count never drops to 1Extra hard links in another directoryfind / -samefile file

Hard links and symlinks are both indirection, but they sit at different layers: a hard link is the filesystem naming one inode twice, and a symlink is a file whose content is a path that every consumer must resolve. Choosing correctly is mostly a question of whether the name must survive a move (hard link), cross a filesystem (symlink), or point at something that does not exist yet (symlink) — and the rest is remembering that the target comes first and that -n, -h, and a trailing slash each change which object a command acts on.

Try matching browser tools

All tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.