Linux ln Command
The Linux ln (full spelling in English: link files) command is a very important command that allows you to create a synchronized link to a file in another location.
When we need to use the same file in different directories, we don't need to place a copy of the file in each directory. Instead, we can place the file in a fixed directory and then use the ln command to create a link to it in other directories, avoiding the need to occupy disk space repeatedly.
Syntax
ln [options][source file or directory][target file or directory]
[-bdfinsvF] [-S backup-suffix] [-V {numbered,existing,simple}]
[--help] [--version] [--]
Command Function:
Neither hard links nor soft links duplicate the original file; they only occupy a very small amount of disk space.
Soft Link:
- Soft links exist in the form of paths. Similar to shortcuts in the Windows operating system.
- Soft links can cross file systems; hard links cannot.
- Soft links can be created for non-existent file names.
- Soft links can be created for directories.
Hard Link:
- Hard links exist in the form of file copies but do not occupy actual space.
- Hard links cannot be created for directories.
- Hard links can only be created within the same file system.
Command Options
Required Options:
- --backup[=CONTROL] Backup existing target files.
- -b Similar to --backup but does not accept parameters.
- -d Allows the superuser to create hard links for directories.
- -f Force execution.
- -i Interactive mode; prompts the user if the file exists.
- -n Treats symbolic links as regular directories.
- -s Soft link (symbolic link).
- -v Displays detailed processing information.
Optional Options:
- -S "-S<backup suffix>" or "--suffix=<backup suffix>"
- -V "-V<backup method>" or "--version-control=<backup method>"
- --help Displays help information.
- --version Displays version information.
Examples
Create a soft link for a file. Create a soft link named link2013 for the file log2013.log. If log2013.log is lost, link2013 will become invalid:
ln -s log2013.log link2013
Output:
[root@localhost test]# ll
-rw-r--r-- 1 root bin 61 11-13 06:03 log2013.log
[root@localhost test]# ln -s log2013.log link2013
[root@localhost test]# ll
lrwxrwxrwx 1 root root 11 12-07 16:01 link2013 -> log2013.log
-rw-r--r-- 1 root bin 61 11-13 06:03 log2013.log
Create a hard link for a file. Create a hard link named ln2013 for the file log2013.log. The properties of log2013.log and ln2013 are identical:
ln log2013.log ln2013
Output:
[root@localhost test]# ll
lrwxrwxrwx 1 root root 11 12-07 16:01 link2013 -> log2013.log
-rw-r--r-- 1 root bin 61 11-13 06:03 log2013.log
[root@localhost test]# ln log2013.log ln2013
[root@localhost test]# ll
lrwxrwxrwx 1 root root 11 12-07 16:01 link2013 -> log2013.log
-rw-r--r-- 2 root bin 61 11-13 06:03 ln2013
-rw-r--r-- 2 root bin 61 11-13 06:03 log2013.log