Difference between soft links and hard links
Intro
A hard link acts as a copy (mirrored) of the selected file. It accesses the data available in the original file. If the earlier selected file is deleted, the hard link to the file will still contain the data of that file.
A soft link (aka Symbolic link) acts as a pointer or a reference to the file name. It does not access the data available in the original file. If the earlier file is deleted, the soft link will be pointing to a file that does not exist anymore.
Inode number
Create a test file:
$ touch testfile
$ echo helloworld > testfile
$ cat testfile
helloworld
Create a hard link:
$ ln testfile testfile1
Create a soft link:
$ ln -s testfile testfile2
Hard link file(testfile1) takes the same inode number.
Soft link file(testfile2) takes a different inode number.
$ ls -li
total 8
658540 -rw-rw-r-- 2 vboxuser vboxuser 11 May 21 20:53 testfile
658540 -rw-rw-r-- 2 vboxuser vboxuser 11 May 21 20:53 testfile1
658543 lrwxrwxrwx 1 vboxuser vboxuser 8 May 21 20:53 testfile2 -> testfile
Directory
Hard link is not allowed for directory while soft link can be created for directory.
$ mkdir testdir
$ ln testdir testdir1
ln: testdir: hard link not allowed for directory
$ ln -s testdir testdir1
$ ls -li | grep testdir
658555 drwxrwxr-x 2 vboxuser vboxuser 4096 May 21 20:58 testdir
658963 lrwxrwxrwx 1 vboxuser vboxuser 7 May 21 20:58 testdir1 -> testdir
Data
Soft link only points to the file name, it does not retain data of the file.
$ ls -la
-rw-rw-r-- 2 vboxuser vboxuser 11 May 21 20:53 testfile
-rw-rw-r-- 2 vboxuser vboxuser 11 May 21 20:53 testfile1
lrwxrwxrwx 1 vboxuser vboxuser 8 May 21 20:53 testfile2 -> testfile
If the original file is removed, the hard link will still work as it accesses the data the original was having access to.
If the original file is removed, the soft link will not work as it doesn’t access the original file’s data.
$ rm -f testfile
$ cat testfile1
helloworld
$ cat testfile2
cat: testfile2: No such file or directory