Conceptcore
Hard links and symbolic links
Also called hard link, symbolic link, symlink, soft link, link count, dangling link, junction, reparse point, shortcut, ln, readlink, lstat.
A hard link is one more name for the same file, and the file stays while one name is left. A symbolic link is a small file that holds a path, which the system follows, so it can dangle or loop.
- Applies to
- core-languages
Idea
A file and its name are two things. The name is an entry in a directory, and it points to the file. A hard link is one more entry that points to the same file, so the file has two names of equal status. A symbolic link is a different kind of file: it holds a path, and the system reads that path when a program opens the link. So a hard link names the file itself, and a symbolic link names a path, which can point to nothing.
import os
with open("data.txt", "w") as f:
f.write("alpha\n")
os.link("data.txt", "hard.txt") # a second name for the same file
os.symlink("data.txt", "soft.txt") # a small file that holds a path
st, hard = os.stat("data.txt"), os.stat("hard.txt")
print("same inode: ", st.st_ino == hard.st_ino)
print("link count: ", st.st_nlink)
print("link target: ", os.readlink("soft.txt"))
print("soft is link:", os.path.islink("soft.txt"), os.path.islink("hard.txt"))
# Remove the first name. The file stays while a hard link names it.
os.remove("data.txt")
print("hard reads: ", open("hard.txt").read().strip())
print("link count: ", os.stat("hard.txt").st_nlink)
print("soft exists: ", os.path.exists("soft.txt"), "(dangling)")
print("soft lexists:", os.path.lexists("soft.txt"))
same inode: True
link count: 2
link target: data.txt
soft is link: True False
hard reads: alpha
link count: 1
soft exists: False (dangling)
soft lexists: True
The two names data.txt and hard.txt have the same inode, so they are one file with a link count of 2. soft.txt holds the string data.txt. When the program removes data.txt, the file stays, because hard.txt still names it, and the count goes down to 1. But soft.txt now holds a path that names nothing, so it is a dangling link: exists follows it and gives False, and lexists looks at the link itself and gives True.
How it works
Hard links. POSIX calls a directory entry a hard link: "A file can have multiple hard links as a result of an execution of the ln utility (without the -s option) or the link () function"1. The link count is "The number of directory entries that refer to a particular file"1. link "shall atomically create a new hard link for the existing file and the link count of the file shall be incremented by one"2. Linux keeps the count in st_nlink, which "contains the number of hard links to the file"6. So unlink and remove remove one name, and the file stays while another name is left, as the idea shows.
A hard link has two limits. Linux says: "Hard links may not refer to directories (to prevent the possibility of loops within the filesystem tree, which would confuse many programs) and may not refer to files on different filesystems (because inode numbers are not unique across filesystems)"7. POSIX gives the error EXDEV when "the implementation does not support hard links between file systems"2.
Symbolic links. POSIX defines a symbolic link as "A type of file with the property that when the file is encountered during pathname resolution, a string stored by the file is used to modify the pathname resolution"1. symlink stores the string as it is: "The string pointed to by path1 shall be treated only as a string and shall not be validated as a pathname"3. Linux says: "a symbolic link is a pointer to another name, and not to an underlying object. For this reason, symbolic links may refer to directories and may cross filesystem boundaries. There is no requirement that the pathname referred to by a symbolic link should exist"7. A link to a path that does not exist "is said to be a dangling link"7.
readlink reads the string. It does not add a NUL byte, and "If the number of bytes in the symbolic link is less than bufsize , the contents of the remainder of buf are unspecified"4. lstat gives the status of the link itself, and for a link, st_size is "the length in bytes of the pathname contained in the symbolic link"5.
Which calls follow a link. Most calls follow a symbolic link, so open and stat act on the target. Some calls act on the link itself: "lchown(2) , lgetxattr(2) , llistxattr(2) , lremovexattr(2) , lsetxattr(2) , lstat(2) , readlink(2) , rename(2) , rmdir(2) , and unlink(2)"7. So unlink removes the link, not its target, and rename moves the link.
Loops. A link can point to itself, or to a link that points back. The system counts the links that it follows: "As currently implemented on Linux, the maximum number of symbolic links that will be followed while resolving a pathname is 40"8. "An ELOOP error is returned when the maximum is exceeded"8.
Windows. NTFS "supports three types of file links: hard links, junctions, and symbolic links"9. A junction "can also link directories located on different local volumes on the same computer"9, and junctions "are implemented through reparse points"9. Symbolic links "are designed to aid in migration and application compatibility with UNIX operating systems"10. A process that is not elevated can make one only with the flag SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, and "Developer Mode must first be enabled on the machine before this option will function"11. A shortcut (a .lnk file) is not a link of the file system. It is "a data object that contains information used to access another object in the Shell's namespace"12, and only the Shell reads it.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Library | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript on Node.js uses the node:fs module, with the types from @types/node, so link, symlink, readlink and lstat are the same as in the JavaScript example. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin on the JVM uses java.nio.file, and the kotlin.io.path package adds extensions of Path such as createLinkPointingTo, createSymbolicLinkPointingTo and readSymbolicLink, so the calls of the Java example do the work. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | SQL works on tables in a database. It does not make or read links in a file system. |
| Bash | Native | The ln command makes a hard link, ln -s makes a symbolic link, and the test -L checks for a symbolic link. GNU and BSD systems also have a readlink command. No example file exists. |
| PowerShell | Native | New-Item with -ItemType HardLink, SymbolicLink or Junction makes a link, and the LinkType and Target properties of an item read it. No example file exists because pwsh is not installed. |
| HTML | Does not apply | A web page cannot make or read a link in the local file system. |
| CSS | Does not apply | CSS gives style rules to a document. It does not make or read files. |
| Regular expressions | Does not apply | A regular expression matches text. It does not make or read links. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | os.link, os.symlink, os.readlink, os.lstat; os.path.islink and os.path.lexists; pathlib.Path.hardlink_to and symlink_to |
| JavaScript | stdlib | Node.js fs.link, fs.symlink with a type for Windows, fs.readlink, fs.lstat |
| TypeScript | stdlib | the node:fs module of Node.js, with the types of @types/node |
| Java | stdlib | Files.createLink, Files.createSymbolicLink, Files.readSymbolicLink, LinkOption.NOFOLLOW_LINKS |
| Kotlin | stdlib | kotlin.io.path extensions such as createSymbolicLinkPointingTo on java.nio.file.Path |
| C# | stdlib | File.CreateSymbolicLink, FileSystemInfo.LinkTarget and ResolveLinkTarget; no hard link call |
| Go | stdlib | os.Link, os.Symlink, os.Readlink, os.Lstat, os.SameFile |
| Rust | stdlib | fs::hard_link, fs::read_link, fs::symlink_metadata; std::os::unix::fs::symlink and the Windows symlink_file and symlink_dir |
| C | library | ISO C has no links; POSIX link, symlink, readlink, lstat, unlink |
| C++ | stdlib | std::filesystem::create_hard_link, create_symlink, read_symlink, hard_link_count, symlink_status |
| Bash | native | the ln and ln -s commands; the test -L; readlink on GNU and BSD systems |
| PowerShell | native | New-Item -ItemType HardLink, SymbolicLink or Junction; the LinkType and Target properties |
| SQL | n/a | a database has no links between files |
| Regex | n/a | a pattern matches text and does not read files |
| HTML | n/a | a page cannot make a link in a file system |
| CSS | n/a | style rules do not read files |
Each language with files has the calls of POSIX: Python's os.link will "Create a hard link pointing to src named dst"13, and os.symlink will "Create a symbolic link pointing to src named dst"13. Go's Link "creates newname as a hard link to the oldname file"17, and Rust's hard_link "currently corresponds to the CreateHardLink function on Windows. On most Unix systems, it corresponds to the linkat function with no flags"18. In Java, both calls are an "optional operation"15, so a file system without links throws an exception.
Windows makes the symbolic link calls differ. A Windows link is for a file or for a directory, so Node.js has a type argument that "is only available on Windows and ignored on other platforms. It can be set to 'dir' , 'file' , or 'junction'"14. Rust has symlink only in the Unix module, where it "Creates a new symbolic link on the filesystem"19, and C++ says: "Portable code should use (3,4) to create directory symlinks rather than (1,2) , even though there is no distinction on POSIX systems"20. .NET has File.CreateSymbolicLink, which "Creates a file symbolic link identified by path that points to pathToTarget"16.
The example files show more: the relative target and the loop in Python, stat and lstat in Node.js, NOFOLLOW_LINKS in Java, a chain of links in C#, SameFile in Go, the link count in Rust, the missing NUL of readlink in C, and symlink_status in C++.
import errno
import os
os.makedirs("sub")
with open("data.txt", "w") as f:
f.write("alpha\n")
# A relative target is read from the directory of the link, not from the
# current directory. So this link points to sub/data.txt, which does not exist.
os.symlink("data.txt", "sub/link")
print("readlink:", os.readlink("sub/link"))
print("exists: ", os.path.exists("sub/link"))
# Two links that point to each other make a loop. The system stops after
# a fixed number of links and gives ELOOP.
os.symlink("b", "a")
os.symlink("a", "b")
try:
os.stat("a")
except OSError as e:
print("loop: ", errno.errorcode[e.errno])
print("lstat: ", os.path.islink("a"))
readlink: data.txt
exists: False
loop: ELOOP
lstat: True
- Verdict: stdlib.
os.link,os.symlinkandos.readlinkare thin wrappers of the POSIX calls, andos.statandos.lstatchoose whether to follow a link.os.path.existsfollows the link andos.path.lexistsdoes not. On Windows,os.symlinkneedstarget_is_directory=Truefor a link to a directory that does not exist yet.
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
int main() {
std::ofstream("data.txt") << "alpha\n";
fs::create_hard_link("data.txt", "hard.txt");
fs::create_symlink("data.txt", "soft.txt");
std::cout << std::boolalpha;
std::cout << "hard_link_count: " << fs::hard_link_count("data.txt") << '\n';
std::cout << "equivalent: " << fs::equivalent("hard.txt", "soft.txt") << '\n';
std::cout << "is_symlink: " << fs::is_symlink("soft.txt") << '\n';
std::cout << "read_symlink: " << fs::read_symlink("soft.txt") << '\n';
fs::remove("data.txt");
std::cout << "exists: " << fs::exists("soft.txt") << '\n';
std::cout << "link there: " << fs::exists(fs::symlink_status("soft.txt")) << '\n';
}
hard_link_count: 2
equivalent: true
is_symlink: true
read_symlink: "data.txt"
exists: false
link there: true
- Verdict: stdlib.
std::filesystemhascreate_hard_link,create_symlink,create_directory_symlink,read_symlink,hard_link_countandequivalent.existsandstatusfollow a link, andsymlink_statusandis_symlinklook at the link itself.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path data = Path.of("data.txt");
Files.writeString(data, "alpha\n");
Path hard = Files.createLink(Path.of("hard.txt"), data);
Path soft = Files.createSymbolicLink(Path.of("soft.txt"), Path.of("data.txt"));
System.out.println("same file: " + Files.isSameFile(hard, soft));
System.out.println("symbolic: " + Files.isSymbolicLink(soft) + " " + Files.isSymbolicLink(hard));
System.out.println("target: " + Files.readSymbolicLink(soft));
Files.delete(data);
System.out.println("hard reads: " + Files.readString(hard).strip());
System.out.println("exists: " + Files.exists(soft));
System.out.println("link there: " + Files.exists(soft, LinkOption.NOFOLLOW_LINKS));
}
}
same file: true
symbolic: true false
target: data.txt
hard reads: alpha
exists: false
link there: true
- Verdict: stdlib.
Files.createLinkandFiles.createSymbolicLinkare optional operations, so a file system that has no links throwsUnsupportedOperationException.Files.existsfollows a link, andLinkOption.NOFOLLOW_LINKSasks about the link itself.
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
FILE *f = fopen("data.txt", "w");
if (f == NULL || fputs("alpha\n", f) < 0 || fclose(f) != 0) return 1;
if (link("data.txt", "hard.txt") != 0 || symlink("data.txt", "soft.txt") != 0) return 1;
struct stat st, lst;
if (stat("soft.txt", &st) != 0 || lstat("soft.txt", &lst) != 0) return 1;
printf("stat: regular %d, nlink %ld\n", S_ISREG(st.st_mode), (long)st.st_nlink);
printf("lstat: link %d, size %ld\n", S_ISLNK(lst.st_mode), (long)lst.st_size);
// readlink does not add a NUL byte, so the code adds it.
char buf[64];
ssize_t n = readlink("soft.txt", buf, sizeof buf - 1);
if (n < 0) return 1;
buf[n] = '\0';
printf("bytes: %zd\n", n);
printf("target: %s\n", buf);
return 0;
}
stat: regular 1, nlink 2
lstat: link 1, size 8
bytes: 8
target: data.txt
- Verdict: library. ISO C has no links. POSIX gives
link,symlink,readlink,lstatandunlink. The size of a symbolic link inlstatis the length of its target, andreadlinkdoes not end the target with a NUL byte.
using System;
using System.IO;
File.WriteAllText("data.txt", "alpha\n");
File.CreateSymbolicLink("link1.txt", "data.txt");
File.CreateSymbolicLink("link2.txt", "link1.txt");
var info = new FileInfo("link2.txt");
Console.WriteLine($"LinkTarget: {info.LinkTarget}");
Console.WriteLine($"one step: {info.ResolveLinkTarget(returnFinalTarget: false)?.Name}");
Console.WriteLine($"final target: {info.ResolveLinkTarget(returnFinalTarget: true)?.Name}");
Console.WriteLine($"Length: {info.Length}");
File.Delete("data.txt");
Console.WriteLine($"File.Exists: {File.Exists("link2.txt")}");
Console.WriteLine($"final exists: {info.ResolveLinkTarget(returnFinalTarget: true)?.Exists}");
LinkTarget: link1.txt
one step: link1.txt
final target: data.txt
Length: 9
File.Exists: True
final exists: False
- Verdict: stdlib.
File.CreateSymbolicLinkandDirectory.CreateSymbolicLinkmake links, andLinkTargetandResolveLinkTargetread them. TheFileclass has no call that makes a hard link, so a program calls the system (linkorCreateHardLink). On Unix, aFileInfofor a link describes the link:Lengthis 9, the length of the target stringlink1.txt, not the 6 bytes ofdata.txt.File.ExistsgivesTruefor a link whose target is gone, so check the final target.
import { link, lstat, readFile, readlink, stat, symlink, unlink, writeFile } from "node:fs/promises";
await writeFile("data.txt", "alpha\n");
await link("data.txt", "hard.txt");
await symlink("data.txt", "soft.txt");
const s = await stat("soft.txt"); // follows the link
const l = await lstat("soft.txt"); // the link itself
console.log("stat isSymbolicLink:", s.isSymbolicLink(), "nlink:", s.nlink);
console.log("lstat isSymbolicLink:", l.isSymbolicLink());
console.log("same inode:", s.ino === (await stat("hard.txt")).ino);
console.log("readlink:", await readlink("soft.txt"));
await unlink("data.txt");
console.log("hard.txt:", (await readFile("hard.txt", "utf8")).trim());
try {
await readFile("soft.txt");
} catch (e) {
console.log("soft.txt:", e.code);
}
stat isSymbolicLink: false nlink: 2
lstat isSymbolicLink: true
same inode: true
readlink: data.txt
hard.txt: alpha
soft.txt: ENOENT
- Verdict: stdlib. Node.js has
fs.link,fs.symlink,fs.readlink, andfs.lstatbesidefs.stat. Thetypeargument ofsymlinkis read only on Windows, where it can be'dir','file'or'junction'.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"syscall"
)
func main() {
if err := os.WriteFile("data.txt", []byte("alpha\n"), 0o644); err != nil {
panic(err)
}
if err := os.Link("data.txt", "hard.txt"); err != nil {
panic(err)
}
if err := os.Symlink("data.txt", "soft.txt"); err != nil {
panic(err)
}
a, _ := os.Stat("data.txt")
h, _ := os.Stat("hard.txt")
l, _ := os.Lstat("soft.txt")
fmt.Println("SameFile: ", os.SameFile(a, h))
fmt.Println("Nlink: ", a.Sys().(*syscall.Stat_t).Nlink)
fmt.Println("Lstat mode: ", l.Mode().Type() == fs.ModeSymlink)
target, _ := os.Readlink("soft.txt")
fmt.Println("Readlink: ", target)
// A link to a directory with the same name again: the system finds a loop.
if err := os.Symlink("loop", "loop"); err != nil {
panic(err)
}
_, err := os.Stat("loop")
fmt.Println("loop: ", errors.Is(err, syscall.ELOOP))
}
SameFile: true
Nlink: 2
Lstat mode: true
Readlink: data.txt
loop: true
- Verdict: stdlib.
os.Link,os.Symlink,os.Readlinkandos.Lstatare in theospackage, andos.SameFilecompares the device and the inode. The link count is not infs.FileInfo, so the example readsNlinkfromsyscall.Stat_t, which exists only on Unix.
use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::{symlink, MetadataExt};
fn main() -> std::io::Result<()> {
fs::write("data.txt", "alpha\n")?;
fs::hard_link("data.txt", "hard.txt")?;
symlink("data.txt", "soft.txt")?;
let data = fs::metadata("data.txt")?;
let hard = fs::metadata("hard.txt")?;
println!("same inode: {}", data.ino() == hard.ino());
println!("nlink: {}", data.nlink());
println!("is_symlink: {}", fs::symlink_metadata("soft.txt")?.file_type().is_symlink());
println!("read_link: {}", fs::read_link("soft.txt")?.display());
fs::remove_file("data.txt")?;
println!("nlink now: {}", fs::metadata("hard.txt")?.nlink());
let gone = fs::metadata("soft.txt").map_err(|e| e.kind());
println!("soft.txt: {:?}", gone.err() == Some(ErrorKind::NotFound));
Ok(())
}
same inode: true
nlink: 2
is_symlink: true
read_link: data.txt
nlink now: 1
soft.txt: true
- Verdict: stdlib.
fs::hard_link,fs::read_linkandfs::symlink_metadataare portable. The call that makes a symbolic link is per system:std::os::unix::fs::symlinkon Unix, andsymlink_fileorsymlink_dirinstd::os::windows::fs. The inode and the link count come from the Unix traitMetadataExt.
Variations and related ideas
- Relative and absolute targets. A relative target is read from the directory of the link, not from the current directory. A link with a relative target keeps working when the directory that holds both moves, and an absolute target keeps working when only the link moves. Linux warns that with a relative path, "moving it to another directory may very well cause it to stop working, since the path may no longer be correct"7.
- Rename and delete. A rename moves one name, and the other hard links do not change. See Rename a file and Delete a file.
- Exists or not. A dangling link exists as a link, but not as a file. The answer depends on whether the call follows the link. See Check whether a file exists.
Pitfalls
- A dangling link looks like a missing file.
openandstatfollow the link, so a link to a removed file gives "no such file". Check withlstatorlexistswhen the difference matters. - A relative target is read from the link.
os.symlink("data.txt", "sub/link")makes a link tosub/data.txt. The Python example shows this. Make the target relative to the link, or make it absolute. - readlink does not end the string. In C,
readlinkgives a count of bytes, and the rest of the buffer is unspecified4. Add the NUL byte yourself, and use a buffer of the size thatlstatgives plus one. - A walk of a tree can loop. A link to a parent directory makes a tree with no end. A walk that follows links must keep the device and inode of each directory that it visits, or not follow links.
- A hard link changes the file for all names. A write through one name changes the data that the other names show. A program that edits a file in place changes each link, and a program that writes a new file and renames it over the old name breaks the hard link.
- A link can let another user choose a file. A program that follows a link in a directory that other users can write to can open or change a file that the other user picks. In such directories, use the calls that act on the link itself7, and check what each name is before the program uses it.
Cost
A hard link is one directory entry, and it uses no new space for the data. A symbolic link is a small file, and each path lookup that meets it reads it and starts again from its target, so each link adds one more lookup. The system stops after 40 links on Linux8.
History
Ritchie and Thompson described links in 1974: "a directory entry for a file is sometimes called a link. The Unix system differs from other systems in which linking is permitted in that all links to a file have equal status. That is, a file does not exist within a particular directory; the directory entry for a file consists merely of its name and a pointer to the information actually describing the file"21. They also wrote: "Thus a file exists independently of any directory entry, although in practice a file is made to disappear along with the last link to it"21. The Wikipedia article on symbolic links reports that they "were introduced in 1982 in 4.1a BSD Unix"22. POSIX now has both kinds1, and Microsoft says that "Symbolic links are available in NTFS starting with Windows Vista"10.
References
- The Open Group, POSIX.1-2024, Base Definitions, Chapter 3, Definitions, 3.168 Hard Link, 3.187 Link, 3.188 Link Count, 3.364 Symbolic Link
- The Open Group, POSIX.1-2024, link, linkat, Description, Errors
- The Open Group, POSIX.1-2024, symlink, symlinkat, Description
- The Open Group, POSIX.1-2024, readlink, readlinkat, Description
- The Open Group, POSIX.1-2024, sys/stat.h, Description, st_size
- inode(7), Linux manual page, Link count
- symlink(7), Linux manual page, Description, Symbolic link ownership, permissions, and timestamps
- path_resolution(7), Linux manual page, Step 2, symbolic links
- Hard links and junctions, Win32 apps, Microsoft Learn, Hard links, Junctions
- Symbolic Links, Win32 apps, Microsoft Learn, Overview, Supported Operating Systems
- CreateSymbolicLinkW function (winbase.h), Win32 apps, Microsoft Learn, Parameters (dwFlags), Remarks
- Shell Links, Win32 apps, Microsoft Learn, About Shell Links
- The Python Standard Library, os, os.link, os.symlink, os.readlink
- Node.js, File system, fsPromises.symlink, type
- Java SE 25 API, java.nio.file.Files, createLink, createSymbolicLink
- File.CreateSymbolicLink(String, String) Method (System.IO), .NET API, Microsoft Learn, Definition
- Go standard library, package os, func Link, func Symlink, func Lstat, func SameFile
- The Rust Standard Library, std::fs::hard_link, Description, Platform-specific behavior
- The Rust Standard Library, std::os::unix::fs::symlink, Description
- std::filesystem::create_symlink, cppreference.com, Description
- D. M. Ritchie and K. Thompson, The UNIX Time-Sharing System (1974, the BSTJ version), 3.2 Directories
- Symbolic link, Wikipedia, History
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag VQ38EM Edit this page History Report an error Markdown