What is a Link in Linux?
A link is a reference to a file. There are two types:
a. Hard Link
- Points directly to the inode (actual data).
- File and hard link are indistinguishable.
- If original is deleted, the data remains (as long as one link exists).
- Cannot span different filesystems or link to directories (by default).
b. Symbolic Link (Soft Link)
- Points to another filename (like a shortcut).
- Can link across filesystems and to directories.
- Breaks if the target is removed or renamed.
Create a Hard Link
Syntax:
ln [source_file] [hard_link_name]Example:
ln file.txt file_hard.txt- Creates a hard link named
file_hard.txtpointing to the same data asfile.txt.
Check link count:
ls -l- Look at the second column – shows number of links to the file’s inode.
Create a Symbolic (Soft) Link
Syntax:
ln -s [target] [link_name]Example (file):
ln -s file.txt file_symlink.txtExample (directory):
ln -s /var/log logsVerify Links
Use ls -l:
ls -lOutput Example:
-rw-r--r-- 2 user user 512 Jul 22 file.txt
-rw-r--r-- 2 user user 512 Jul 22 file_hard.txt
lrwxrwxrwx 1 user user 9 Jul 22 file_symlink.txt -> file.txt- Hard link: same inode count, identical size
- Symlink: shows
->pointing to the target
Differences Between Hard and Symbolic Links
| Feature | Hard Link | Symbolic (Soft) Link |
|---|---|---|
| Points to | Inode (actual data) | File name (path) |
| Survives original? | Yes | No (broken link if deleted) |
| Across filesystems? | No | Yes |
| Can link directories? | No (by default) | Yes |
| Command | ln | ln -s |
Removing Links
-
Removing symlink:
rm file_symlink.txt -
Removing hard link:
rm file_hard.txt(Original data exists as long as at least one link remains)
Summary
Link Commands Summary (Linux)
| Task | Command | Notes |
|---|---|---|
| Create a hard link | ln source_file hard_link | Cannot be used on directories (default) |
| Create a symbolic (soft) link | ln -s target_path symlink_name | Works for files and directories |
| Create symlink to a file | ln -s file.txt link.txt | link.txt points to file.txt |
| Create symlink to a directory | ln -s /var/log logs | logs points to /var/log |
| List all links with details | ls -l | Symbolic links show -> target |
| View inode numbers (verify hard links) | ls -li | Same inode = hard link |
Check link type with file | file filename | Identifies symlink, text, binary, etc. |
| Remove a symbolic link | rm symlink_name | Only deletes the link, not the target |
| Remove a hard link | rm hard_link | Data stays if at least one link remains |
Last updated on