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
- Know how to move around the tree (
ls,cd,rm) - Understand the difference between an absolute and a relative path
- A shell, no particular privilege
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:
echo "original content" > report.txtls -li report.txt8591538 -rw-r--r--. 1 ansible ansible 17 Jul 23 10:04 report.txtThe 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.
What is a hard link?
A hard link adds a directory entry that points to an existing inode. It copies nothing.
ln report.txt report-copy.txtls -li report.txt report-copy.txt8591538 -rw-r--r--. 2 ansible ansible 17 Jul 23 10:04 report-copy.txt8591538 -rw-r--r--. 2 ansible ansible 17 Jul 23 10:04 report.txtTwo 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.
echo "line appended" >> report-copy.txtcat report.txtoriginal contentline appendedAnd deleting a name destroys nothing as long as another one remains:
rm report.txtls -li report-copy.txtcat report-copy.txt8591538 -rw-r--r--. 1 ansible ansible 31 Jul 23 10:04 report-copy.txtoriginal contentline appendedThe 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):
stat -c 'links=%h inode=%i' a.txtfind ~/lab-links -inum 8591547links=3 inode=8591547/home/ansible/lab-links/a.txt/home/ansible/lab-links/b.txt/home/ansible/lab-links/c.txtIt 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.
What are the two limits of a hard link?
The hard link has two strict constraints, which come straight from its nature.
ln folder folder-linkln: folder: hard link not allowed for directoryNo 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.
ln ~/report.txt /dev/shm/testln: failed to create hard link '/dev/shm/test' => '/home/ansible/report.txt':Invalid cross-device linkNo 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.
What is a symbolic link?
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".
echo "payload" > target.txtln -s target.txt shortcut.txtls -li target.txt shortcut.txt8591540 -rw-r--r--. 1 ansible ansible 8 Jul 23 10:04 target.txt8591541 lrwxrwxrwx. 1 ansible ansible 10 Jul 23 10:04 shortcut.txt -> target.txtEverything 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:
readlink shortcut.txt # the target as writtenreadlink -f shortcut.txt # the final path, all links resolvedThe -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.
Relative or absolute link: where is the target read from?
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:
cd ~ln -s report.txt /tmp/linkcat /tmp/linkThe 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.
What is a broken link?
Since a symbolic link only contains a path, nothing guarantees that the path exists. Delete the target, and the link becomes broken (dangling):
rm target.txtls -l shortcut.txtcat shortcut.txtlrwxrwxrwx. 1 ansible ansible 10 Jul 23 10:04 shortcut.txt -> target.txtcat: shortcut.txt: No such file or directoryThe 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:
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:
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.
The table then sums up the properties that decide between the two.
| Criterion | Hard link | Symbolic link |
|---|---|---|
| Inode | the same as the target | its own, distinct |
| To a directory | impossible | possible |
| To another filesystem | impossible | possible |
| If the target is deleted | the data survives | the link is broken |
Visible in ls -l | indistinguishable from a file | arrow -> and type l |
| Typical use | backups, deduplication | current 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.
ln -sfn /opt/app-2.4.1 /opt/app-currentScripts 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.
Which four link traps should you know?
These four behaviours produce no explicit error, or a message that misleads you. They are worth seeing once before you meet them in production.
rm -r link/ destroys the target's contents
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.
mkdir target-dir && touch target-dir/f1 target-dir/f2ln -s target-dir link-dirrm -r link-dir/rm: cannot remove 'link-dir/': Not a directoryThe 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:
ls target-dir | wc -l0Both 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.
ln -sf does not replace a link to a directory
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.
ln -s v1 currentln -sf v2 currentreadlink currentv1The 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:
ls v1v2The -n option (--no-dereference) fixes the behaviour by treating current as a link and not as a directory:
ln -sfn v2 currentreadlink currentv2Remember 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.
ls -l l.txt # lrwxrwxrwx, like every linkchmod -h 600 l.txtecho $?stat -c %a l.txt0777The 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.
cp without -d copies the target, not 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:
cp link.txt copy.txttest -L copy.txt && echo "link" || echo "regular file"regular filecp followed the link and copied the target's contents. To keep the link as a link, you need -d (or -a, which includes it):
cp -d link.txt copy.txttest -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.
Security: which kernel protections apply to links?
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.
sysctl fs.protected_hardlinks fs.protected_symlinksfs.protected_hardlinks = 1fs.protected_symlinks = 1fs.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.
sudo -u otheruser ln /tmp/root-file /tmp/stolen-linkln: failed to create hard link '/tmp/stolen-link' => '/tmp/root-file':Operation not permittedfs.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.
How do you inspect the links in a tree?
A few inventory commands, useful during an audit or a migration.
# All symbolic linksfind /opt -type l
# Only broken linksfind /opt -xtype l
# Files that have several names (hard links)find /home -type f -links +1
# Walk the tree following linksfind -L /opt -type fTroubleshooting
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.
| Symptom | Likely cause | Fix |
|---|---|---|
No such file or directory although ls shows the link | Broken link: the target is gone or was moved | readlink -f <link> to see the destination, then recreate the link |
| A link works, then breaks after a move | The link was created with a relative path, read from the directory of the link: once the link is moved, that path points elsewhere | Recreate it with an absolute path, or move the link and its target together |
hard link not allowed for directory | Hard link to a directory | Use ln -s |
Invalid cross-device link | Hard link between two filesystems | Use ln -s |
Operation not permitted on an ln | fs.protected_hardlinks: you do not own the target and do not have both read and write permission on it | Go through the owner, or use a symbolic link |
ln -sf returns 0 but the link still points to the same place | The target is a directory, a link was created inside it | Use ln -sfn, and clean up the stray link it created |
A directory's contents vanished after an rm | rm -r link/ with a trailing slash | Restore from backup; never put a trailing / on a link |
chmod on a link changes nothing | A link's permissions are never checked on Linux | Set the permissions of the target or the parent directory |
| After a copy, the link became a regular file, or it is gone | cp without -d or -r followed the link; rsync -r without -l skipped it | Use 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 llists broken links. ls -lisettles it in one command: same inode for a hard link, typeland an arrow for a symbolic link.rm -r link/with a trailing slash empties the target directory while printingNot 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. chmodon a link is useless on Linux, andcpwithout-dor-rcopies the target instead of the link.fs.protected_hardlinksandfs.protected_symlinksare 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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Work with files and text on Linux
A new full quiz with random questions
Work again only on the questions you missed