basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Symlinks, hardlinks, and their equivalents: Linux, Windows, and macOS

    A symlink stores a text path to a file or directory; a hardlink is a second name for the same file on disk. Alongside them, filesystems and kernels provide mount --bind, copy-on-write clones (reflink), OverlayFS, and Windows junctions — each with its own scope and limits.

    In Linux filesystems (ext4, XFS, Btrfs), a file’s name and its data are stored separately. A directory is a table mapping names to inode numbers. The inode itself stores metadata (size, permissions, owner, timestamps, link count) and pointers to data blocks on disk.

    Hardlink: two names point to the same inode
    
      /srv/data/archive.tar.gz ──┐
                                 ├──► [ inode | Links: 2 ] ──► data blocks on disk
      /srv/backup/archive.tar.gz ┘
    
    Symlink: separate inode storing a path string
    
      /etc/nginx/sites-enabled/site.conf ──► [ own inode | path: "../sites-available/site.conf" ]
                                                                         │
                                                                         ▼
      /etc/nginx/sites-available/site.conf ──► [ target inode | Links: 1 ] ──► data blocks
    ln -s

    Symlink (symbolic link)

    file holding a path

    A small separate file with its own inode storing the target path. When a program opens the symlink, the kernel reads that path and follows it. Works for directories and across filesystems; if the target is deleted or moved, the stored path doesn’t update and the link turns dangling.

    ln

    Hardlink

    second name for the same inode

    Another directory entry pointing to the same inode number. Neither name is the “original”: both point to the same data blocks and increment Links. Disk blocks are freed only when Links hits zero and no process still has the file open. Works only for files within the same filesystem.

    Beyond classic links, Linux and other OSes have four more mechanisms that expose files in another location, save disk space, or merge directories. People often confuse them with symlinks and hardlinks.

    mount --bind

    Bind mount

    kernel level · Linux

    Mounts an existing directory or file at a second point in the tree. Works across partitions and inside chroot, SFTP, and containers where an outside symlink breaks. You can mark the second mount point read-only.

    cp --reflink / cp -c

    Reflink (CoW clone)

    copy-on-write · Btrfs, XFS, APFS

    Not a link, but two independent files with separate inodes sharing the same blocks on disk. No extra space is used at copy time, and editing one file doesn’t affect the other: on write, the filesystem copies only the changed blocks.

    mount -t overlay

    OverlayFS

    directory layers · Linux

    Stacks a writable upper directory (upperdir) on top of a read-only lower directory (lowerdir), presenting them to processes as one merged tree (merged). This is what backs Docker container layers and Live-USB images.

    .lnk · .desktop · Alias

    GUI shortcut

    regular file · desktop shell

    Not a filesystem link, just a regular file interpreted by the desktop environment (Explorer, Finder, desktop menu). CLI tools, cat, git, and scripts read it literally as text or binary bytes.

    Bind mounts in practice

    Expose a directory at a second path and optionally make that second view read-only (keeping the original writable):

    sudo mount --bind /srv/media /var/www/files
    sudo mount -o remount,ro,bind /var/www/files

    This mount lasts until reboot. To restore it automatically at boot, add a line to /etc/fstab:

    /srv/media  /var/www/files  none  bind,ro  0  0

    Use this to clone a VM image or database before running an experiment — you can edit or delete the clone without touching the original:

    cp --reflink=always /srv/images/vm.raw /srv/images/vm-test.raw

    On Linux, reflink works within a single partition on Btrfs, XFS (with reflink=1, default since Ubuntu 20.04), and OpenZFS 2.2+. ext4 doesn’t support it — --reflink=always returns Operation not supported. Starting with GNU coreutils 9.0, plain cp defaults to --reflink=auto: it creates an instant CoW clone where supported and falls back to a normal copy on ext4. On macOS (APFS), the same feature is cp -c for files and cp -cR for directories; on Windows, CoW clones exist only on server ReFS (not standard NTFS).

    OverlayFS layers

    lowerdir (read-only: base image)           ──┐
                                                 ├──► merged (what the process sees)
    upperdir (writable: edits and new files)   ──┘

    You rarely run mount -t overlay by hand, but the model explains why a container’s directory looks unified even though its files live across different layers on disk: it’s a layered mount, not symlinks.

    All six mechanisms side by side

    Mechanism Layer Directories & cross-disk Permissions & disk space Deleting or editing target
    Symlink (ln -s) filesystem yes, both target permissions (lrwxrwxrwx ignored); space for path string link breaks; edits modify target
    Hardlink (ln) filesystem no — files on one partition only shared inode & permissions; 0 extra blocks data stays while Links > 0; save-via-mv breaks link
    Bind mount kernel (mount point) yes, both; works in chroot & containers second point can be ro; 0 extra blocks active while mounted; gone on reboot without fstab
    Reflink (cp --reflink) filesystem (CoW) files (dirs too on APFS), one partition separate inodes & permissions; space only for diffs files are independent: editing or deleting one leaves the other intact
    OverlayFS kernel (layers) directories; layers can differ upper layer stores only edits and whiteouts lower layer untouched; writes go to upperdir
    Shortcut (.lnk, .desktop, Alias) desktop shell yes, both regular file with its own permissions CLI programs don’t follow it at all

    Commands on Linux

    ln takes arguments in the same order as cp and mv: target first (the existing file or directory), then the new link name. If the second argument is an existing directory, ln creates the link inside it using the target’s name.

    An absolute symlink (such as enabling an nginx site):

    ln -s /etc/nginx/sites-available/site.conf /etc/nginx/sites-enabled/site.conf

    If the directory might move or get mounted into a container, use a relative symlink. Pass -r (--relative) so ln computes the ../ path from the link’s location to the target instead of counting levels by hand:

    ln -sr /etc/nginx/sites-available/site.conf /etc/nginx/sites-enabled/site.conf
    ls -l /etc/nginx/sites-enabled/site.conf
    # lrwxrwxrwx 1 root root 30 … /etc/nginx/sites-enabled/site.conf -> ../sites-available/site.conf

    Create a hardlink with the same command minus -s (both paths on the same filesystem):

    ln /srv/data/archive.tar.gz /srv/backup/archive.tar.gz
    ls -li /srv/data/archive.tar.gz /srv/backup/archive.tar.gz
    # first column shows the same inode number for both paths; third column shows link count 2

    Replace a file symlink with -f (--force):

    ln -sf /etc/nginx/sites-available/site-v2.conf /etc/nginx/sites-enabled/site.conf

    When the target is a directory, -f alone isn’t enough: ln follows the existing symlink into the directory and places the new link inside it. Add -n (--no-dereference) to replace the symlink itself:

    ln -sfn /srv/releases/v2 /srv/current

    ln -sfn unlinks the old symlink and then creates the new one, leaving a sub-millisecond gap where /srv/current doesn’t exist. Under live traffic where you need a strictly atomic swap, create a temporary link next to it and swap them with a single rename via mv -Tf (-T stops mv from moving the link into the old directory):

    ln -s /srv/releases/v2 /srv/current.new && mv -Tf /srv/current.new /srv/current

    Remove either a symlink or a hardlink with unlink or rm — the target file stays untouched. unlink takes exactly one path, removes only the link itself, and never descends into a directory.

    unlink /srv/current

    Diagnostic commands

    Command What it does
    ls -li <path> inode number, type (l for symlink), hardlink count, and -> target
    stat <path> full inode fields: Inode, Links, permissions, timestamps
    readlink -f <link> final absolute path resolved through the full symlink chain
    namei -l <path> walks each path component, showing every symlink hop and its permissions
    find /etc/nginx -xtype l finds broken symlinks in a directory
    find /srv -samefile /srv/data/archive.tar.gz finds all hardlinks to the same inode under /srv

    Gotchas: Docker, editors, and permissions

    path visibility

    Docker volumes

    A container sees only its own filesystem and mounted volumes. If /opt/app/data contains a symlink pointing to /etc/app/secret.conf, it works on the host but breaks inside the container. Relative symlinks (ln -sr) pointing inside the same volume work in both places.

    new inode

    Editors and atomic saves

    sed -i, git pull, default rsync, and many editors save files by writing a temporary copy and running mv. The filename gets a new inode while the second hardlink keeps the old contents. The same mechanism breaks single-file mounts in Docker (Single-file mounts).

    target vs link

    chmod and chown

    ls -l always shows lrwxrwxrwx on a symlink, while actual access comes from the target’s permissions. chmod and chown follow symlinks to the target; to change ownership of the link itself, pass -h: sudo chown -h example-user:example-user /srv/current.

    How Linux, Windows, and macOS compare

    All three systems support symlinks and hardlinks, but their commands, limits, and privilege rules differ sharply.

    Mechanism Linux (ext4 / XFS / Btrfs) Windows (NTFS) macOS (APFS)
    File symlink ln -s <target> <link> mklink <link> <target> ln -s <target> <link>
    Directory symlink ln -s <target> <link> mklink /D <link> <target> ln -s <target> <link>
    Hardlink (files only) ln <target> <link> mklink /H <link> <target> ln <target> <link>
    Non-symlink directory link mount --bind (needs root) Junction: mklink /J (no admin) Firmlink (OS-only)
    CoW clone (reflink) cp --reflink=auto (Btrfs, XFS, ZFS) ReFS only (not NTFS) cp -c / cp -cR (APFS)
    GUI shortcut .desktop .lnk Finder Alias (survives target moves)
    Admin rights for symlink not required required unless Developer Mode is on not required

    Windows (NTFS)

    Coming from Linux, four NTFS differences trip people up most often:

    • mklink reverses the argument order: new link name first, target second.
    • Directory symlinks require the /D flag. Without it, Explorer and programs won’t open the path.
    • Creating symlinks requires administrator privileges (SeCreateSymbolicLinkPrivilege) by default. To let normal programs and git create them without elevation, enable Developer Mode in Windows 10/11 Settings (For developers).
    • mklink is a cmd.exe built-in and doesn’t exist in PowerShell — use New-Item or cmd /c mklink ... there.
    # PowerShell: symlink, junction, and hardlink
    New-Item -ItemType SymbolicLink -Path C:\work\app.conf -Target D:\configs\app.conf
    New-Item -ItemType Junction     -Path C:\work\logs     -Target D:\data\logs
    New-Item -ItemType HardLink     -Path C:\work\copy.txt -Target C:\work\orig.txt
    :: cmd.exe: same operations plus listing all hardlinks of a file
    mklink    C:\work\app.conf D:\configs\app.conf
    mklink /D C:\work\dir-link D:\configs
    mklink /J C:\work\logs     D:\data\logs
    mklink /H C:\work\copy.txt C:\work\orig.txt
    fsutil hardlink list C:\work\orig.txt

    NTFS also has junctions (mklink /J), directory reparse points for local folders. A junction stores an absolute path and doesn’t work with files or network shares (\\server\share), but needs no administrator rights even with Developer Mode off — which is why pnpm, scoop, and many Windows installers use junctions. Remove one in cmd with rmdir C:\work\logs: it removes only the junction itself and leaves target files untouched.

    If Git was installed on Windows without symlink privileges, core.symlinks defaults to false, and git clone writes repo symlinks as plain text files containing the target path. Flash drives formatted as FAT32 or exFAT support no links at all — no symlinks, hardlinks, or junctions. Inside WSL2, Linux rules apply on the ext4 root filesystem, while mounted Windows drives under /mnt/c/... create NTFS-compatible links.

    macOS (APFS)

    macOS sits on a POSIX/BSD base, so ln -s and ln work much like Linux with four differences:

    • BSD ln and mv lack GNU -r (--relative) and -T. Replacing a directory symlink works with ln -sfn (or -sfh; in BSD -h is a synonym for -n). If you need GNU flags, run brew install coreutils and call gln -sr and gmv -Tf.
    • APFS supports CoW clones natively (cp -c and cp -cR, see Reflink above); duplicating files in Finder on the same volume uses the same mechanism.
    • Directory hardlinks are forbidden on APFS just like on Linux (the old HFS+ exception for Time Machine is gone; Time Machine now uses APFS snapshots).
    • Beyond POSIX links, macOS has Finder Alias (a GUI file storing both path and file ID so it survives moving the target, though terminals treat it as a plain file) and Firmlinks — an internal OS feature introduced in macOS 10.15 Catalina that bridges the read-only system volume / and /System/Volumes/Data into unified paths like /Users and /Applications; users can’t create firmlinks themselves.

    Which one to pick

    If you need to… Pick
    enable an nginx config, systemd unit, or switch a release directory symlink (ln -s, for a directory — ln -sfn)
    point to a directory or file on another partition or drive symlink (ln -s)
    keep two names for one file on the same partition so deleting one preserves the other hardlink (ln)
    save space in incremental backups (rsync --link-dest) or file seeding hardlink (ln)
    expose one directory in two places, including inside chroot, SFTP, or a container mount --bind
    make an independent copy of a large file without extra disk space (Btrfs, XFS, APFS) reflink (cp --reflink=auto / cp -c)
    link a local directory on Windows without administrator rights junction (mklink /J)

    Trade-offs

    What you get

    • Single source of truth. A config, library, or archive lives in one place while appearing at multiple paths without duplication.
    • Instant version switches. Replacing a symlink (ln -sfn or mv -Tf) moves an app to a new release or rolls it back without copying directories.
    • Disk savings. Hardlinks and reflink store incremental backups and image clones while consuming space only for changed data.

    What it costs

    • Broken links after moves. Rename or relocate the target, or point outside a Docker volume, and a symlink silently stops resolving.
    • Silent hardlink splits on edit. Tools like sed -i and git pull replace the file with a new inode, leaving the other hardlink stale.
    • OS and filesystem gaps. Admin rights and core.symlinks on Windows, missing -r/-T on macOS, and no link support on FAT32/exFAT break cross-platform scripts and repos.

    Where to start

    1. For everyday server tasks, default to symlinks (ln -s), and use relative symlinks (ln -sr) inside portable projects or Docker volumes.
    2. Update directory symlinks with ln -sfn (or atomically with mv -Tf), and remove them with unlink without a trailing slash.
    3. On Windows, if you work with repos containing symlinks, enable Developer Mode once and run git config --global core.symlinks true; for local directories without admin rights, use junctions (mklink /J).
    4. See how hardlinks and symlinks diverge after deleting the original in ten seconds inside a Linux temp directory:
    tmp=$(mktemp -d)
    echo "v1" > "$tmp/orig.txt"
    ln "$tmp/orig.txt" "$tmp/hard.txt"
    ln -s "$tmp/orig.txt" "$tmp/sym.txt"
    
    ls -li "$tmp"
    # orig.txt and hard.txt share the same inode number and link count 2; sym.txt has its own inode and -> .../orig.txt
    
    rm "$tmp/orig.txt"
    cat "$tmp/hard.txt"
    # v1
    cat "$tmp/sym.txt"
    # cat: .../sym.txt: No such file or directory
    
    rm -rf "$tmp"

    If it doesn’t work

    You created a relative symlink, ls highlights it in red, and cat says No such file or directory

    Cause
    A relative path inside a symlink is resolved from the directory holding the link itself, not the working directory where you ran ln.
    Fix
    Recreate the link with an absolute path or -r (ln -sr), so ln computes the relative path from the link to the target.

    ln -sf /srv/releases/v2 /srv/current didn’t update the link and created a nested v2 link inside v1

    Cause
    Without -n, ln follows the existing directory symlink and places the new link inside it.
    Fix
    Remove the stray /srv/releases/v1/v2 link and update current with -n: ln -sfn /srv/releases/v2 /srv/current.

    ln returns Invalid cross-device link

    Cause
    The source file and the new link live on different filesystems or partitions. Inode numbers are per filesystem, so a hardlink can’t cross that boundary.
    Fix
    Use a symlink (ln -s) — it stores a path and works across partitions.

    ln returns hard link not allowed for directory

    Cause
    The kernel forbids directory hardlinks so the filesystem tree can’t form infinite loops.
    Fix
    Use a symlink (ln -s) for directories, or mount --bind if you need a mount point elsewhere.

    You deleted a large file, yet df -h shows the same disk usage

    Cause
    Another hardlink still points to the same inode (stat showed Links above 1), or a running process still holds the file open.
    Fix
    Find remaining names with find / -samefile <file> before deleting, or check open deleted files with sudo lsof +L1 and restart the process.

    You edited a file with sed -i or vim, but its hardlink still has the old content

    Cause
    sed -i, git pull, and many editors save changes by writing a temp file and running mv: the original filename now points to a new inode while the hardlink stays on the old one.
    Fix
    To keep the link intact, overwrite the same file in place (cp new file, cat new > file) or recreate the hardlink. The same behavior breaks single-file mounts in Docker (Single-file mounts).

    Opening a file or entering a directory returns Too many levels of symbolic links

    Cause
    Symlinks form a loop: a link points to itself or to another link that points back.
    Fix
    Trace the chain with namei -l <path> or ls -la, delete the looping link, and recreate it with the right target.

    A symlink opens on the host, but fails inside a Docker container

    Cause
    The link points to an absolute host path or escapes the mounted volume — that path doesn’t exist inside the container.
    Fix
    Create a relative symlink (ln -sr) inside the same volume directory, or mount the target directory into the container at the same path.

    On Windows, git clone checked out a symlink as a plain text file containing one path line

    Cause
    Git has core.symlinks off, or the user lacks permission to create NTFS symlinks.
    Fix
    Turn on Developer Mode in Windows Settings, run git config --global core.symlinks true, and refresh the working tree (git checkout -- .).

    On Windows, mklink fails with You do not have sufficient privilege to perform this operation

    Cause
    Creating symlinks on NTFS requires administrator privileges (SeCreateSymbolicLinkPrivilege) by default.
    Fix
    For a local directory, use a junction (mklink /J) — no elevation required. For a symlink, enable Developer Mode in Windows or run the terminal as Administrator.

    On macOS, ln -sr and mv -Tf fail with illegal option

    Cause
    macOS ships BSD ln and mv, which lack GNU flags -r and -T.
    Fix
    Write the relative path manually in ln -s, or install GNU coreutils via Homebrew and run gln -sr and gmv -Tf.