Creating Soft and Hard Links with ln in Linux
In Linux, every file is associated with an inode—an index node storing metadata such as size, timestamps, ownership, and a pointer to the actual data blocks. The inode serves as the true identifier for a file; filenames are merely references. File contents reside in data blocks referenced via their inode.
List a file's inode using ls -i:
$ ls -i
31615656 AndroidStudioProjects 30836545 go
1152719 Applications 49115578 images
31827389 CNode 13208576 ktsgs.zip
595399 Desktop 44722768 pandoc_demo
595275 Documents 49218456 pgadmin.log
595277 Downloads 15078624 pomelo
7094352 LevelTest 1009499 project
7098493 LevelTest.zip 1011801 qdb
595388 Library 5901898 qdb.zip
595439 Movies 23150187 test
595441 Music 1010768 tmp
595443 Pictures 17956310 trunk
595445 Public 17970255 trunk.zip
32072972 app 41999857 webwork
1009500 code 13208610 游戏配置
22509232 databak
The leading number on each line is the inode value.
Linking mechanisms provide alternate access paths to a file, similar to shortcuts in Windows, implemented via the ln command.
Command syntax:
ln [option] target_path link_name
Options:
-f— Force removal of existing destination files before linking.-i— Prompt before overwriting an existing file.
Symbolic Link (Soft Link)
Create with:
ln -s src_file sym_link
A symbolic link is an independent file with its own inode. Its data block stores the pathname of the target file rather than the file's actual contents. Characteristics:
- Each symbolic link possesses a distinct inode.
- Can reference both regular files and directories.
- May span different filesystems.
- Removing the link leaves the target intact; deleting the target renders the link unusable (dangling).
Hard Link
Create with:
ln src_file hard_link
A hard link creates an additional directory entry pointing to the same inode and physical data as the original file. Apart from the name, it shares all metadata and content with the source. Essentially, the file acquires an additional filename.
Charatceristics:
- Shares the identical inode with the original file.
- Referencse the exact same data blocks.
- Can only be created for existing regular files (not directories).
- Removing one link does not affect others; data persists until all links are removed.
- Limited to the same filesystem.