A link to a file means referring the same file by different filenames. In Linux and Unix-based system, the following two types of links exist:
To create links between files, the ln
command can be used. The syntax is as follows:
ln [option] target link_name
Here, target
is the filename for which a link has to be created and link_name
is the name by which a link has to be created.
A soft link is a special kind of file that just points to another file. This makes it easier to create a shortcut of a file and easy accessibility of a file to a different location in a filesystem.
To create a symbolic link of a file, the ln
command is used with the -s
option. For example, we will create a symbolic link of the /tmp
directory in our home directory:
$ ln -s /tmp ~/local_tmp
Now, we have a symbolic link of the /tmp
directory in our home directory by the name local_tmp
. To access the /tmp
data, we can also cd
into the ~/local_tmp
directory. To know whether a file is a symbolic link or not, run ls -l
on a file:
$ ls -l ~/local_tmp lrwxrwxrwx. 1 foo foo 5 Aug 23 23:31 /home/foo/local_tmp -> /tmp/
If the first character of the first column is l
, then it means it is a symbolic link. Also the last column says /home/foo/local_tmp -> /tmp/
, which means local_tmp
is pointing to /tmp
.
A hard link is a way to refer a file with different names. All such files will have the same inode number. An inode number is an index number in an inode table that contains metadata about a file.
To create a hard link of a file, use the ln
command without any option. In our case, we will first create a regular file called file.txt
:
$ touch file.txt $ ls -l file.txt -rw-rw-r--. 1 foo foo 0 Aug 24 00:13 file.txt
The second column of ls
tells the link count. We can see that currently it is 1
.
Now, to create a hard link of file.txt
, we will use the ln
command:
$ ln file.txt hard_link_file.txt
To check whether a hard link is created for file.txt
, we will see its link count:
$ ls -l file.txt -rw-rw-r--. 2 foo foo 0 Aug 24 00:13 file.txt
Now, the link count is 2
because a hard link has been created with the name hard_link_file.txt
.
We can also see that the inode number of the file.txt
and hard_link_file.txt
files are the same:
$ ls -i file.txt hard_link_file.txt 96844 file.txt 96844 hard_link_file.txt
The following table shows a few important differences between a hard link and a soft link:
Soft link |
Hard link |
---|---|
The inode number of the actual file and the soft link file are different. |
The inode number of the actual file and the hard link file are the same. |
A soft link can be created across different filesystems. |
A hard link can only be created in the same filesystem. |
A soft link can link to both regular files and directories. |
A hard link doesn't link to directories. |
Soft links are not updated if the actual file is deleted. It keeps pointing to a nonexistent file. |
Hard links are always updated if the actual file is moved or deleted. |
18.217.0.127