Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Hard links and symbolic links on Linux

By updated

Improve this page

A link gives a file a second name, without duplicating it. Linux offers two kinds, which look alike in use but have nothing in common internally: the hard link, a real extra name for the same data, and the symbolic link, a mere signpost that contains a path. This guide shows how to create both with ln, how to tell them apart by their inode (the number that identifies a file on the disk), how to spot a broken link, and above all how to avoid the command that silently wipes the target's contents, that is, the file or directory the link designates. All outputs come from a test on AlmaLinux 10.

What you will learn

  • Create a hard link and a symbolic link with ln
  • Tell the two apart through the inode and the link count
  • Choose which one to use for a given need
  • Spot and repair a broken symbolic link
  • Avoid the four traps that cost data or time

Prerequisites

Why is a file not the same thing as its name?

To understand links, you first have to drop an intuitive idea: on Linux, a file and its name are two separate things.

The permissions, the dates, the owner and the location of the data blocks on the disk (the pieces where the data is written) are recorded in a structure called an inode, identified by a unique number on the filesystem. The inode does not contain the data itself: it says where the data is. The name is only an entry in a directory, pointing to that inode number.

A directory is therefore a phone book: it maps names to numbers. Nothing prevents two names from designating the same number, and that is exactly what a hard link is.

Create a small file, then display its inode number:

Terminal window
echo "original content" > report.txt
ls -li report.txt
8591538 -rw-r--r--. 1 ansible ansible 17 Jul 23 10:04 report.txt

The first column, added by the -i option, is the inode number. The figure right after the permissions, here 1, is the link count: the number of names that designate this inode. These two values are the key to everything that follows.

A hard link adds a directory entry that points to an existing inode. It copies nothing.

Terminal window
ln report.txt report-copy.txt
ls -li report.txt report-copy.txt
8591538 -rw-r--r--. 2 ansible ansible 17 Jul 23 10:04 report-copy.txt
8591538 -rw-r--r--. 2 ansible ansible 17 Jul 23 10:04 report.txt

Two observations go together. The inode number is identical (8591538): this is not a copy, it is the same file. And the link count went from 1 to 2, because two names now designate it.

The consequence follows logically: editing one edits the other, since there is only one file.

Terminal window
echo "line appended" >> report-copy.txt
cat report.txt
original content
line appended

And deleting a name destroys nothing as long as another one remains:

Terminal window
rm report.txt
ls -li report-copy.txt
cat report-copy.txt
8591538 -rw-r--r--. 1 ansible ansible 31 Jul 23 10:04 report-copy.txt
original content
line appended

The count is back to 1, the data is intact. This explains how rm really works: the command removes a name and decrements the count. The data is only released when the count reaches zero, and no process holds the file open.

How do you find every name of the same file?

Since several names can coexist, it is worth knowing how to find them. Take a file a.txt that carries three names. stat -c prints the link count (%h) and the inode (%i), then find -inum lists every name that designates that inode (replace the number with the one stat prints on your machine):

Terminal window
stat -c 'links=%h inode=%i' a.txt
find ~/lab-links -inum 8591547
links=3 inode=8591547
/home/ansible/lab-links/a.txt
/home/ansible/lab-links/b.txt
/home/ansible/lab-links/c.txt

It is also the reflex to have when directory sizes look surprising. GNU du counts a file that carries several names only once: it charges its size to the first name it meets, so to the directory walked first, and a directory total can change with the order of the arguments. Only the -l option (--count-links) counts the size of every name.

The hard link has two strict constraints, which come straight from its nature.

Terminal window
ln folder folder-link
ln: folder: hard link not allowed for directory

No hard link to a directory. The ban protects the system: directories pointing at each other would create infinite loops in the tree, which traversal tools could not handle.

Second try: /dev/shm is a directory held in RAM, so a different filesystem from your home directory. The example reuses report.txt; recreate it in your home directory if you deleted it above.

Terminal window
ln ~/report.txt /dev/shm/test
ln: failed to create hard link '/dev/shm/test' => '/home/ansible/report.txt':
Invalid cross-device link

No hard link between two filesystems. An inode number only makes sense inside a given filesystem: inode 8591538 on your disk and the same number on a USB stick have nothing to do with each other. The message Invalid cross-device link is explicit once you know the reason.

A symbolic link (symlink, or soft link) is a file in its own right, with its own inode, whose content is simply a path. It is a signpost that says "what you are looking for is over there".

Terminal window
echo "payload" > target.txt
ln -s target.txt shortcut.txt
ls -li target.txt shortcut.txt
8591540 -rw-r--r--. 1 ansible ansible 8 Jul 23 10:04 target.txt
8591541 lrwxrwxrwx. 1 ansible ansible 10 Jul 23 10:04 shortcut.txt -> target.txt

Everything differs from the previous case. The inodes differ (8591540 and 8591541), the file type is l at the start of the permissions, and ls -l shows the arrow to the destination. The size of 10 bytes is no accident: it is the length of the string target.txt.

Symbolic links lift both limits of the hard link: they cross filesystems and point to directories. That is why a symbolic link is most often the right choice.

The check to run after every ln -s fits in one command. readlink prints the destination stored in the link, without following it, which shows exactly what was written rather than what you think you asked for:

Terminal window
readlink shortcut.txt # the target as written
readlink -f shortcut.txt # the final path, all links resolved

The -f form goes to the end of the chain and resolves every link it meets: it is the one that answers when a link points to another link, a frequent case with stacked version links.

A symbolic link contains a path, and that path can be absolute (it starts with /) or relative (it does not). A relative path is read from the directory that contains the link, not from the directory where you typed ln. The difference only shows once the link is created elsewhere:

Terminal window
cd ~
ln -s report.txt /tmp/link
cat /tmp/link

The link records the path report.txt as is. When you read /tmp/link, the system looks for /tmp/report.txt, which does not exist: cat answers No such file or directory and ls -l /tmp/link shows link -> report.txt. The link is broken from the moment it is created, although report.txt does exist in your home directory. With the target as an absolute path (ln -s ~/report.txt /tmp/link), the link works from anywhere; with a relative path, it works as long as the link and its target keep the same position relative to each other.

Since a symbolic link only contains a path, nothing guarantees that the path exists. Delete the target, and the link becomes broken (dangling):

Terminal window
rm target.txt
ls -l shortcut.txt
cat shortcut.txt
lrwxrwxrwx. 1 ansible ansible 10 Jul 23 10:04 shortcut.txt -> target.txt
cat: shortcut.txt: No such file or directory

The link is still there, ls shows it without blinking, but nothing answers at the other end. Two tests tell the cases apart in a script:

Terminal window
test -e shortcut.txt && echo "the target exists" || echo "broken link"
test -L shortcut.txt && echo "it is a link"

-e follows the link and fails if the target is missing; -L tests the existence of the link itself. A broken link therefore answers "no" to the first and "yes" to the second, which sets it apart from a file that is really absent.

To sweep a whole tree, find has a dedicated predicate:

Terminal window
find /opt -xtype l

-xtype l only returns links whose target no longer exists, in other words broken links. It is the inventory command after a migration or an uninstall.

Hard or symbolic: which one should you choose?

The symbolic link is the common choice, because it crosses filesystems, it can point to a directory, and ls -l shows its target. The diagram takes the two examples from this page: on the left, two names point to the same inode, whose link count is 2; on the right, the symbolic link has its own inode, which holds nothing but a path.

On the left, report.txt and report-copy.txt point to the same inode 8591538, which holds the data and counts two links. On the right, shortcut.txt points to its own inode 8591541, which holds the path target.txt; that path leads to inode 8591540, which holds the data.report.txtreport-copy.txt     inode 8591538     data · links: 2shortcut.txtinode 8591541content: “target.txt”target.txt follows the path      inode 8591540     dataHard link:two names, one inodeSymbolic link:a file thatholds a pathfile nameinode holding the datainode holding a pathname to its inodefollows the stored path
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The table then sums up the properties that decide between the two.

CriterionHard linkSymbolic link
Inodethe same as the targetits own, distinct
To a directoryimpossiblepossible
To another filesystemimpossiblepossible
If the target is deletedthe data survivesthe link is broken
Visible in ls -lindistinguishable from a filearrow -> and type l
Typical usebackups, deduplicationcurrent versions, configuration shortcuts

A typical pattern in administration is the version symlink: a stable path that points to the running version, redirected during an update without touching the scripts that use it.

Terminal window
ln -sfn /opt/app-2.4.1 /opt/app-current

Scripts reference /opt/app-current, and an update comes down to pointing the link elsewhere. -s creates a symbolic link and -f replaces an existing link. Note the -n option too: the second of the four traps below explains why it is not optional.

These four behaviours produce no explicit error, or a message that misleads you. They are worth seeing once before you meet them in production.

It is the most serious one, because it loses data silently behind a reassuring message. The combination at fault is precise: a symbolic link to a directory, a trailing slash, and the -r option.

Terminal window
mkdir target-dir && touch target-dir/f1 target-dir/f2
ln -s target-dir link-dir
rm -r link-dir/
rm: cannot remove 'link-dir/': Not a directory

The message announces a failure and the exit code of rm is 1 (every program leaves this number when it ends, echo $? prints it, and 0 means everything went well). And yet:

Terminal window
ls target-dir | wc -l
0

Both files are gone. The trailing slash made rm follow the link: it emptied the target directory, then failed while trying to delete the link itself, hence the message. The link and the directory survive, their contents do not.

The usual reflex to redirect an existing link is ln -sf. It works for a link to a file, and fails silently for a link to a directory. To try it, first create two directories with mkdir v1 v2.

Terminal window
ln -s v1 current
ln -sf v2 current
readlink current
v1

The exit code is 0, and yet current still points to v1. The command read current as the destination directory and created a link inside the target:

Terminal window
ls v1
v2

The -n option (--no-dereference) fixes the behaviour by treating current as a link and not as a directory:

Terminal window
ln -sfn v2 current
readlink current
v2

Remember ln -sfn as the default form to redirect a link: it suits a link to a file as well as a link to a directory.

chmod -h succeeds and does nothing

You might think you can harden a link by changing its permissions with chmod, the command that changes the access rights of a file (the permissions module covers it). On Linux, this has no effect at all. The example starts from a link l.txt to an existing file, created with touch file.txt && ln -s file.txt l.txt.

Terminal window
ls -l l.txt # lrwxrwxrwx, like every link
chmod -h 600 l.txt
echo $?
stat -c %a l.txt
0
777

The exit code is 0, no message appears, and the permissions did not move. The reason is simple: the Linux kernel never checks the permissions of a symbolic link, only those of the target count. The -h option only exists in GNU coreutils chmod since version 9.5: an older version, such as the one in Ubuntu 24.04, answers invalid option -- 'h'. It exists to stay compatible with other Unix systems that do take the permissions of a link into account.

What really protects is therefore setting the permissions of the target, or those of the directory that holds the link.

Copying a symbolic link does not give you a symbolic link. To try it, create link.txt with ln -s file.txt link.txt, with file.txt already existing:

Terminal window
cp link.txt copy.txt
test -L copy.txt && echo "link" || echo "regular file"
regular file

cp followed the link and copied the target's contents. To keep the link as a link, you need -d (or -a, which includes it):

Terminal window
cp -d link.txt copy.txt
test -L copy.txt && echo "link preserved"

In a recursive copy, the tools behave differently. GNU coreutils cp -r copies the links found inside the tree as they are, and tar also archives them as links. cp -r even keeps a link given directly as an argument, whereas cp without -r follows a link to a file (and fails on a broken link) or refuses a link to a directory.

For a backup, rsync -r alone skips links and prints skipping non-regular file: you need -l, or -a which includes it, to keep them.

Links have long been an attack vector, especially in shared directories such as /tmp. The Linux kernel ships two protections, enabled by default on modern distributions. This section talks about owner and access rights, which the permissions module covers: read it as an overview, without trying to reproduce the example that needs a second account.

Terminal window
sysctl fs.protected_hardlinks fs.protected_symlinks
fs.protected_hardlinks = 1
fs.protected_symlinks = 1

fs.protected_hardlinks forbids creating a hard link to a file you do not own, unless you have both read and write permission on it. Without it, a user could create a link to a sensitive file, wait for a privileged process to change its permissions, and end up with access they should never have had.

Terminal window
sudo -u otheruser ln /tmp/root-file /tmp/stolen-link
ln: failed to create hard link '/tmp/stolen-link' => '/tmp/root-file':
Operation not permitted

fs.protected_symlinks plays the same role for symbolic links. In a world-writable directory that carries the sticky bit (the bit that restricts deleting or renaming a file to its owner, the directory owner and root), such as /tmp, a symbolic link is only followed if its owner is the one following it, or the owner of the directory.

A few inventory commands, useful during an audit or a migration.

Terminal window
# All symbolic links
find /opt -type l
# Only broken links
find /opt -xtype l
# Files that have several names (hard links)
find /home -type f -links +1
# Walk the tree following links
find -L /opt -type f

Troubleshooting

When a link does not do what you expect, start with these cases. The table sorts them by observable symptom, since that is what you have at the moment of the problem.

SymptomLikely causeFix
No such file or directory although ls shows the linkBroken link: the target is gone or was movedreadlink -f <link> to see the destination, then recreate the link
A link works, then breaks after a moveThe link was created with a relative path, read from the directory of the link: once the link is moved, that path points elsewhereRecreate it with an absolute path, or move the link and its target together
hard link not allowed for directoryHard link to a directoryUse ln -s
Invalid cross-device linkHard link between two filesystemsUse ln -s
Operation not permitted on an lnfs.protected_hardlinks: you do not own the target and do not have both read and write permission on itGo through the owner, or use a symbolic link
ln -sf returns 0 but the link still points to the same placeThe target is a directory, a link was created inside itUse ln -sfn, and clean up the stray link it created
A directory's contents vanished after an rmrm -r link/ with a trailing slashRestore from backup; never put a trailing / on a link
chmod on a link changes nothingA link's permissions are never checked on LinuxSet the permissions of the target or the parent directory
After a copy, the link became a regular file, or it is gonecp without -d or -r followed the link; rsync -r without -l skipped itUse cp -d or cp -a; with rsync, use -l or -a

Put it into practice

Creating a link takes two seconds; telling one kind from the other without mistakes takes a little practice. The lab has you create a hard link that shares the inode, a symbolic link that points by path, and then a symbolic link to a directory. The validation checks the inode, the link count and the target of each link, exactly what ls -li shows you.

Key points

  • A file is an inode; a name is only a directory entry that points to it.
  • A hard link is one more name for the same inode: same contents, data kept as long as one name remains. Impossible to a directory or to another filesystem.
  • A symbolic link contains a path. It crosses filesystems, points to directories, and becomes broken if the target disappears.
  • A relative path in a symbolic link is read from the directory that contains the link: move the link alone, and it can break. find /opt -xtype l lists broken links.
  • ls -li settles it in one command: same inode for a hard link, type l and an arrow for a symbolic link.
  • rm -r link/ with a trailing slash empties the target directory while printing Not a directory. The three other forms are safe.
  • To redirect a link, write ln -sfn: without -n, a link to a directory is not replaced, and a new link is created inside the target directory.
  • chmod on a link is useless on Linux, and cp without -d or -r copies the target instead of the link.
  • fs.protected_hardlinks and fs.protected_symlinks are protections to keep, even though their error messages do not name them.

Knowledge check

Check that the essentials of this guide stuck. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer