PREP WITH PROOF
Menu
LINUX & INFRASTRUCTURE / PRACTICAL GUIDE

Linux Hard Links vs Symbolic Links: Diagnose Broken Paths

Diagnose Linux hard links and symlinks with inode identity, relative paths, file replacement and unlink behavior. Includes a reproducible 26-check local lab.

THE QUICK ANSWER

A hard link is another name for the same file object; a symbolic link stores a pathname that is resolved when followed. Compare device/inode identity, inspect the stored target relative to the link’s directory, and distinguish writing an object from replacing a pathname. The included Linux fixture demonstrates why renaming, saving and deleting can produce different outcomes.

Start with names, objects and paths

A deployment shortcut opens yesterday’s configuration. A relative link says “No such file or directory” even though the file exists. An editor saves a change, but a supposedly linked copy still contains the old text. These symptoms involve different relationships. Identify which relationship you created before changing permissions or recreating files.

A hard link gives an existing file another directory entry. Both names refer to the same filesystem object; neither has special original-file status. A symbolic link is a separate object containing a target pathname. Opening that pathname normally follows the link, while inspecting or removing the link can act on the link itself.

This guide focuses on ordinary Linux regular files and GNU coreutils. The examples use disposable files owned by the current user. They do not require sudo, alter protected-link settings, or touch a live deployment. Special procfs links, network filesystem caching and application-specific file handling require separate investigation.

QuestionHard linkSymbolic link
What is shared?The underlying file objectA pathname is stored in a separate link
Target renamed?Other hard names remain usableStored pathname may stop resolving
Target pathname replaced?Existing hard name still refers to old objectFollowing the pathname can reach the replacement
Different filesystem?Cannot span filesystem boundariesMay reference a path across them
Directory target?Ordinary directory hard links are prohibitedDirectory symlinks are supported

Source: Linux man-pages: symlink handling ↗

Inspect both the link and the resolved target

For a suspicious path, collect the stored link text and two sets of metadata. GNU stat examines the symlink itself by default; stat -L follows it. The device/inode pair identifies the resolved object for this observation. An inode number alone is insufficient when comparing different filesystems.

Compare report.txt and report-hard.txt using the same non-following command. For regular files, matching device and inode values show that the two names currently identify the same object. The hard-link count reports names referring to that object; it is not the number of processes reading it, nor a history of every alias ever created.

If readlink prints a pathname but stat -L fails, do not conclude that readlink repaired or validated the destination. It has reported what the link stores. Check each directory component and the caller’s access. A missing component, denied directory traversal and a symbolic-link cycle need different corrections. Inspect as the account running the application whenever possible.

# GNU tools; inspect paths you already know.
readlink -- shortcuts/report-good
stat -c 'device=%d inode=%i links=%h type=%F name=%n' -- shortcuts/report-good
stat -L -c 'device=%d inode=%i links=%h type=%F name=%n' -- shortcuts/report-good
stat -c 'device=%d inode=%i links=%h type=%F name=%n' -- data/report.txt data/report-hard.txt

Source: GNU coreutils: stat invocation ↗

A relative target starts at the link’s directory

The most useful relative-link question is: “If I stand in the directory containing this link, where does its stored text lead?” It is not resolved relative to the terminal directory from which ln happened to run. A successful ln -s exit therefore proves link creation, not successful target resolution.

Consider a workspace containing data/report.txt and a shortcuts directory. From the workspace root, ln -s data/report.txt shortcuts/report-bad stores data/report.txt inside the link. Following it looks under shortcuts/data/report.txt. The intended relative target is ../data/report.txt. The lab below creates both forms and verifies that one resolves while the other dangles.

Choose relative paths when the link and target will move together without changing their internal layout. Choose an absolute pathname when the reference should remain anchored at a particular root-visible location. Neither choice guarantees portability into another container or mount namespace. An absolute path meaningful on the host can be absent inside the process that follows it.

GNU ln --relative can calculate a relative symbolic target, but inspect the generated result: its canonicalization can resolve intervening symlinks. For a learning example, writing the short target explicitly makes the intended relationship visible. For automation, document whether an alias should follow a stable release name or remain attached to a particular release directory.

Source: GNU coreutils: ln invocation and relative/destination options ↗

An in-place write differs from replacing a pathname

Our first lab mutation writes through the hard-link name. The source name and the good symlink both read the changed bytes. That is the expected shared-object behavior. It also explains why a hard link is not an independent backup: an application that truncates and rewrites the shared object changes what both hard names read.

The next mutation renames the source. The hard name still works, but the symlink’s old pathname dangles. Creating a fresh file at the old pathname makes the symlink usable again; it now reaches a different object. The hard name still reads the earlier object. Calling the result a stale cache would hide the actual cause.

The fixture then uses os.replace to replace the source pathname with a prepared file in the same temporary directory. The symlink reads the replacement, while the old hard name retains the earlier contents. This reproduces the distinction relevant to applications that save by replacing a file rather than modifying its existing object.

Do not assume that every editor, copy command or configuration generator uses the same save strategy. Observe its behavior in an isolated directory using object identity and contents before and after saving. If two paths unexpectedly diverge, ask whether the writer replaced one pathname. If two paths unexpectedly change together, ask whether they still share an object.

Source: Linux man-pages: link(2) ↗

Run the complete disposable-file experiment

Save the following as links_lab.py and run python3 links_lab.py on Linux with GNU ln, stat and readlink available. It creates one temporary workspace and cleans that workspace on exit. The commands create and remove only its own invented files; no production filename or privileged directory is involved.

The checks deliberately assert relationships rather than fixed inode numbers, which differ between runs. They compare both identity and content, distinguish a link’s own metadata from followed metadata, and assert ELOOP for a two-link cycle. Two negative CLI cases check that a directory hard link is rejected and an existing regular destination survives a default symbolic-link attempt.

In our Linux execution with GNU coreutils 9.4, all 26 checks passed. This is a reproducible local fixture, not a claim that every filesystem, editor or deployment system behaves identically. We did not mount another filesystem to test EXDEV, run permission scenarios under another account, or test Windows shortcuts.

import errno
import os
from pathlib import Path
import stat
import subprocess
import tempfile

checks = 0

def check(value, label):
    global checks
    if not value:
        raise AssertionError(label)
    checks += 1

def run(*args, ok=True):
    result = subprocess.run(args, text=True, capture_output=True)
    if ok and result.returncode:
        raise RuntimeError(result.stderr)
    return result

def identity(path):
    s = path.stat()
    return s.st_dev, s.st_ino

with tempfile.TemporaryDirectory(prefix='pwp-links-') as directory:
    root = Path(directory)
    data, shortcuts, moved = [root / n for n in ('data', 'shortcuts', 'moved')]
    for p in (data, shortcuts, moved):
        p.mkdir()
    source = data / 'report.txt'
    source.write_text('version one\n')
    hard = data / 'report-hard.txt'
    good = shortcuts / 'report-good'
    bad = shortcuts / 'report-bad'
    run('ln', '--', str(source), str(hard))
    run('ln', '-s', '--', '../data/report.txt', str(good))
    run('ln', '-s', '--', 'data/report.txt', str(bad))
    check(identity(source) == identity(hard), 'hard-link identity')
    check(source.stat().st_nlink == 2, 'two hard names')
    check(good.lstat().st_ino != source.stat().st_ino, 'separate symlink inode')
    check(identity(good) == identity(source), 'followed symlink identity')
    check(os.readlink(good) == '../data/report.txt', 'stored relative text')
    check(good.read_text() == 'version one\n', 'good relative resolution')
    check(bad.is_symlink() and not bad.exists(), 'wrong relative target dangles')
    check(run('readlink', '--', str(bad)).stdout.strip() == 'data/report.txt', 'readlink works on dangling link')
    check(run('stat', '-c', '%F', '--', str(good)).stdout.strip() == 'symbolic link', 'GNU stat examines link')
    check(run('stat', '-L', '-c', '%d:%i', '--', str(good)).stdout.strip() == run('stat', '-c', '%d:%i', '--', str(source)).stdout.strip(), 'GNU stat -L follows target')
    hard.write_text('shared edit\n')
    check(source.read_text() == good.read_text() == 'shared edit\n', 'in-place write through hard name')
    source.rename(data / 'renamed.txt')
    check(hard.read_text() == 'shared edit\n', 'hard name survives rename')
    check(good.is_symlink() and not good.exists(), 'symlink dangles after target rename')
    source.write_text('new object\n')
    check(good.read_text() == 'new object\n', 'same pathname now resolves new object')
    check(identity(source) != identity(hard), 'recreated target is different object')
    replacement = data / 'replacement.txt'
    replacement.write_text('replacement\n')
    os.replace(replacement, source)
    check(good.read_text() == 'replacement\n', 'replacement visible through pathname link')
    check(hard.read_text() == 'shared edit\n', 'old hard link retains old object')
    good.unlink()
    check(source.read_text() == 'replacement\n', 'unlink symlink preserves target')
    (data / 'renamed.txt').unlink()
    check(hard.stat().st_nlink == 1, 'one remaining hard name')
    with hard.open() as handle:
        hard.unlink()
        check(not hard.exists(), 'last hard pathname removed')
        check(handle.read() == 'shared edit\n', 'open descriptor remains readable')
        check(os.fstat(handle.fileno()).st_nlink == 0, 'open object has zero links')
    moved_link = moved / 'report'
    run('ln', '-s', '--', '../data/report.txt', str(moved_link))
    deeper = moved / 'deep'
    deeper.mkdir()
    moved_link.rename(deeper / 'report')
    check((deeper / 'report').is_symlink() and not (deeper / 'report').exists(), 'moving relative link changes base')
    run('ln', '-s', '--', 'loop-b', str(root / 'loop-a'))
    run('ln', '-s', '--', 'loop-a', str(root / 'loop-b'))
    try:
        (root / 'loop-a').read_bytes()
    except OSError as error:
        check(error.errno == errno.ELOOP, 'cycle reports ELOOP')
    else:
        raise AssertionError('cycle unexpectedly readable')
    result = run('ln', '--', str(data), str(root / 'hard-directory'), ok=False)
    check(result.returncode != 0, 'directory hard link rejected')
    existing = root / 'existing'
    existing.write_text('keep me\n')
    result = run('ln', '-s', '--', str(source), str(existing), ok=False)
    check(result.returncode != 0 and existing.read_text() == 'keep me\n', 'default does not replace destination')
print(f'PASS: {checks} checks')
print(run('ln', '--version').stdout.splitlines()[0])

Repair the relationship that is actually wrong

For a dangling relative link, preserve its stored text as evidence and calculate the intended path from its containing directory. Confirm the intended destination before replacing anything. A typo is different from an intentionally absent future release. A symlink can exist before its target, so creation time alone does not settle that question.

For a destination collision, inspect whether the destination is a regular file, a real directory or a symlink to a directory. GNU ln can treat a directory destination as a place to create a link inside. Its -T option makes the final operand a single destination rather than a target directory; it does not by itself authorize overwriting. Avoid adding -f reflexively when the current object has not been identified.

For “Invalid cross-device link,” choose whether you need another name for the same object or an independent copy. Hard links cannot cross filesystems, including separate mount situations described by Linux link semantics. A symlink may meet the naming requirement only if its pathname is visible to the consumer. Copying meets a different requirement and introduces synchronization questions.

For permission failures, a readable target filename is not enough: the process must traverse the directories on the resolved route. A symlink’s familiar mode display is not a grant of access to its target. Keep the correction narrow and verify with the actual service account; changing permissions recursively can obscure the original failure.

The practical habit is to record three facts before repair: the stored target text, the resolved device/inode pair, and the operation that last changed the pathname. Together they explain whether you have a broken route to a file, two names for shared data, or a name that now resolves to a replacement. That evidence makes the next change small and testable.

Source: Linux man-pages: pathname resolution ↗

KEEP THESE THREE THINGS

Your next steps

  1. Use readlink and both stat modes to separate the link from its destination.
  2. Test whether a writer changes the shared object or replaces one pathname before choosing a repair.
  3. Reproduce changes with disposable files; a hard link is shared data, not an independent backup.

Sources & official resources

Linked resources checked on 2026-10-31. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →