Difference between soft links & hard links in Linux

0
1714

Soft Link

A soft link (symbolic link or a symlink) makes it possible to associate one file with another. It is similar to a shortcut in MS Windows where the actual file is resident somewhere in the directory structure but you may have multiple shortcuts or pointers with different names pointing to it. This means accessing the file via the actual file name or any of the shortcuts would yield an identical result. Each soft link has a unique inode number.

A soft link can cross file system boundaries and can be used to link directories.

To create a soft link for unix-admin as sys-admin in the same directory, use the ln command with the -s option

nextstep4it@localhost:~$ cd /home/nextstep4it/
nextstep4it@localhost:~$ ln -s unix-admin sys-admin

where:

  • unix-admin is an existing file
  • sys-admin is soft linked to unix-admin

After you have created the link, issue ll with -i option. Notice the letter l as the first character in the second column of the output. Also notice an arrow pointing from the linked file to the original file. This indicates that sys-admin is merely a pointer to unix-admin. The -i option displays associated inode numbers in the first column.

nextstep4it@localhost:~$ ll -i
3674110 lrwxrwxrwx 1 nextstep4it nextstep4it 10 Jan 12 11:03 sys-admin -> unix-admin
3674109 -rw-rw-r-- 1 nextstep4it nextstep4it 0 Jan 12 11:03 unix-admin

If you remove the original file (unix-admin in this example), the link sys-admin will stay but points to something that does not exist.

Hard Link

A hard link associates two or more files with a single inode number. This allows the files to have identical permissions, ownership, time stamp, and file contents. Changes made to any of the files are reflected on the other linked files. All files actually contain identical data.

A hard link cannot cross file system boundaries and cannot be used to link directories.

The following example uses the ln command and creates a hard link for “ubuntu-rocks” file located under /home/nextstep4it to “debian-os” in the same directory. Note that “debian-os” file does not exist, but it will be created.

nextstep4it@localhost:~$ cd /home/nextstep4it/
nextstep4it@localhost:~$ ln ubuntu-rocks debian-os

After creating the link, run ll with the -i option:

nextstep4it@localhost:~$ ll -i
3674110 -rw-rw-r-- 2 nextstep4it nextstep4it 40 Jan 12 11:15 debian-os
3674110 -rw-rw-r-- 2 nextstep4it nextstep4it 40 Jan 12 11:15 ubuntu-rocks

Look at the first and the third columns. The first column indicates that both files have identical inode numbers and the third column tells that each file has two hard links. “ubuntu-rocks”’ points to “debian-os” and vice versa. If you remove the original file (ubuntu-rocks in this example), you will still have access to the data through the linked file debian-os.

LEAVE A REPLY