# Create and change hard and symbolic links

> Give one file several names with hard links, point to it with symlinks, tell them apart, and know when to link instead of copy.

Source: https://aminbytes.dev/bytes/devices-and-filesystems/links/


Sometimes you want one file to show up in two places. A config that several programs read, the "current" version of a release, a short name for a long path. Copying would give you two files that drift apart. A **link** gives you one file with more than one way to reach it.

Linux has two kinds, and they work very differently: **hard links** and **symbolic links** (symlinks, soft links). You'll find both all over a normal system.

## First: names and inodes

In [an earlier byte](../filesystem-integrity/) you met the **inode**: the record that holds a file's data location, size, owner and permissions. What it doesn't hold is the file's **name**. Names live in directories: a directory is a list of "name → inode number" pairs.

So a file name is already a link: it links a name to an inode. `ls -i` shows the inode number:

```console
$ echo hello > original.txt
$ ls -i original.txt
1835012 original.txt
```

## Hard links: a second name for the same inode

`ln TARGET LINKNAME` adds another name for the same inode:

```console
$ ln original.txt hard.txt
$ ls -li
total 8
1835012 -rw-r--r-- 2 alex alex 6 Dec  1 10:00 hard.txt
1835012 -rw-r--r-- 2 alex alex 6 Dec  1 10:00 original.txt
```

Look at two things. The inode number is the same: these are not two files, they're two names for one file. And the number after the permissions, the **link count**, went from 1 to 2.

Neither name is the "original" anymore. They're equal. Change the contents through one and you see it through the other, because there's only one set of data:

```console
$ echo world >> hard.txt
$ cat original.txt
hello
world
$ rm original.txt
$ cat hard.txt
hello
world
```

Removing a name only lowers the link count. The data is freed when the count reaches 0 and no process has it open. That's why the system call for deleting is literally called `unlink`, and there's an `unlink` command too.

Hard links have two limits:

```console
$ ln hard.txt /mnt/usb/hard.txt
ln: failed to create hard link '/mnt/usb/hard.txt' => 'hard.txt': Invalid cross-device link
$ ln mydir dirlink
ln: mydir: hard link not allowed for directory
```

- **Same filesystem only.** Inode numbers are only unique inside one filesystem.
- **No directories.** That would allow loops in the tree. (The `.` and `..` entries are the only directory hard links, and only the filesystem makes those.)

 (Side note: That's also why a directory's link count is never 1. An empty directory has 2: its name in the parent, and its own `.`. Every subdirectory adds one more, through its `..`.)

## Symbolic links: a pointer to a path

`ln -s TARGET LINKNAME` creates a symlink: a tiny separate file that just contains a path.

```console
$ ln -s hard.txt soft.txt
$ ls -li
total 4
1835013 -rw-r--r-- 1 alex alex 12 Dec  1 10:01 hard.txt
1835015 lrwxrwxrwx 1 alex alex  8 Dec  1 10:02 soft.txt -> hard.txt
```

- Its own inode number, and type `l`.
- The arrow shows where it points. Its size, 8, is the length of the path `hard.txt`.
- Permissions always show `rwxrwxrwx`. They don't matter: the target's permissions are what count.

Programs that open a symlink are sent on to the target automatically. Because it's only a path, a symlink **can** point to a directory, cross to another filesystem, and even point at something that doesn't exist. If you remove the target, the symlink stays behind, **dangling** (broken):

```console
$ rm hard.txt
$ cat soft.txt
cat: soft.txt: No such file or directory
```

> [!IMPORTANT]
> A relative symlink target is resolved from the **link's** directory, not from where you ran `ln`. `ln -s notes.txt /tmp/n` creates `/tmp/n -> notes.txt`, which looks for `/tmp/notes.txt`. Use an absolute path, or `ln -sr` to let ln work out the right relative path for you.

## Useful ln options

| Option | Does |
| --- | --- |
| `-s` | make a symbolic link (without it, ln makes a hard link) |
| `-f` | replace the link name if it already exists |
| `-i` | ask before replacing |
| `-n` | if the link name is a symlink to a directory, replace it instead of going into it |
| `-r` | with `-s`, make the target relative to the link's location |
| `-v` | print what it does |

The `-n` one matters when you **change** where a symlink to a directory points. Without it, ln follows the old link and creates the new one *inside* the directory:

```console
$ ln -s releases/v1 current
$ ln -sfn releases/v2 current
$ ls -l current
lrwxrwxrwx 1 alex alex 11 Dec  1 10:20 current -> releases/v2
```

You can also give ln a directory as the last argument. `ln -s /opt/tool/bin/tool ~/bin/` creates `~/bin/tool`.

## Telling links apart

| Clue | Hard link | Symbolic link |
| --- | --- | --- |
| `ls -l` type | `-` (like any file) | `l` |
| `ls -l` arrow | no | `name -> target` |
| inode (`ls -i`) | same as the other names | its own |
| link count | 2 or more | usually 1 |
| crosses filesystems | no | yes |
| points to directories | no | yes |
| survives deleting the target | yes, it **is** the file | no, it dangles |

A few more tools help:

```console
$ readlink current
releases/v2
$ readlink -f current
/home/alex/app/releases/v2
$ echo data > a.txt; ln a.txt b.txt
$ stat -c '%h %i %n' a.txt b.txt
2 1835020 a.txt
2 1835020 b.txt
$ find . -samefile a.txt
./a.txt
./b.txt
$ find . -type l
./current
$ find . -xtype l
./soft.txt
```

`readlink` prints where a symlink points and `-f` resolves the whole chain to the final real path. `stat` shows the link count (`%h`) and inode (`%i`). `find -samefile` (or `-inum`) finds all hard links of a file, `-type l` finds symlinks, and GNU find's `-xtype l` finds **broken** ones.

## Copying versus linking

| | `cp` | hard link | symlink |
| --- | --- | --- | --- |
| New inode and data | yes | no | new inode, no data copy |
| Changes show in both | no | yes | yes |
| Uses extra space | yes, full size | no | a few bytes |
| Independent afterwards | yes | no | no |

Copy when you want an independent version, like a backup before editing. Link when you want one source of truth.

`cp` has link-related options too: `cp -l` makes hard links instead of copies, `cp -s` makes symlinks, and `cp -a` (or `-d`) copies symlinks **as symlinks**. A plain `cp link dest` follows the link and copies the target's contents.

## Links in system administration

Once you know them, you see links everywhere:

```console
$ ls -l /bin /etc/localtime /etc/alternatives/editor
lrwxrwxrwx 1 root root  7 Jan 28  2024 /bin -> usr/bin
lrwxrwxrwx 1 root root 18 Jun 18 09:12 /etc/alternatives/editor -> /usr/bin/vim.basic
lrwxrwxrwx 1 root root 33 Jun 18 09:10 /etc/localtime -> /usr/share/zoneinfo/Europe/Berlin
```

- **Merged /usr**: on current Debian, Ubuntu, RHEL and Fedora, `/bin`, `/sbin` and `/lib` are symlinks into `/usr`.
- **Alternatives**: `/usr/bin/editor` points to `/etc/alternatives/editor`, which points to the editor you picked. `update-alternatives` (Debian) or `alternatives` (RHEL) switches the second link.
- **Time zone**: `/etc/localtime` is a symlink into `/usr/share/zoneinfo/`.
- **Shared libraries**: `libz.so.1 -> libz.so.1.2.13`. Programs ask for `libz.so.1` and don't care about the exact version behind it.
- **Enabling things**: `systemctl enable` creates symlinks in `/etc/systemd/system/*.wants/`. SysV init used links like `/etc/rc3.d/S20ssh -> ../init.d/ssh`. Debian's nginx and Apache enable sites by linking `sites-enabled/` to `sites-available/`.
- **Deployments**: a `current -> releases/v2` symlink, switched with `ln -sfn`, lets you roll back by pointing it at the old release.
- **Device names**: the `/dev/disk/by-uuid/` and `by-label/` entries from the mounting byte are symlinks made by udev.

## Exam checklist

- `ln target name` makes a hard link, `ln -s target name` makes a symlink. Order: target first, new name second (like `cp`).
- Hard link: same inode, link count goes up, same filesystem only, no directories, survives deleting the other name.
- Symlink: own inode, type `l`, shows `->`, can cross filesystems and point to directories, breaks if the target goes away.
- Relative symlink targets are resolved from the link's directory. `ln -sr` computes them for you.
- `ln -f` overwrites, `ln -sfn` safely repoints a symlink to a directory.
- Identify with `ls -l` (type and arrow), `ls -li` (inode), `stat`, `readlink -f`, `find -samefile`/`-inum`, `find -type l`.
- `cp` makes an independent copy. `cp -a`/`-d` keeps symlinks as links, `cp -l` and `cp -s` make links.


## Byte check

1. You run `ln report.txt copy.txt`, then `rm report.txt`. What happens to `copy.txt`?
   - It becomes a broken link
   - It's deleted too
   - **It still works: the data stays until the last name is removed** (correct)
   A hard link is a second name for the same inode. The data is only freed when the link count drops to 0.

2. Which of these can a **symbolic** link do that a hard link can't?
   - Keep the data alive after the original is deleted
   - **Point to a directory or to a file on another filesystem** (correct)
   - Share the same inode number as its target
   Hard links must stay on the same filesystem and can't point to directories. A symlink just stores a path, so it can point anywhere.

3. In `ls -li`, how do you spot two names that are hard links to the same file?
   - Both start with `l`
   - **They show the same inode number and a link count of 2 or more** (correct)
   - One shows `->` pointing at the other
   Hard links are equal names for one inode. The `l` type and the `->` arrow belong to symbolic links.


