What is the difference between a hard link and a symbolic link?
Let’s start with what’s similar about the two. A hard link is a reference to the same piece of data, or the inode. Hard links were introduced to UNIX to give it a hierarchal filesystem. So they don’t have size or speed penalties because they’re built into the structure.
One of the best ways to see this is:
$ ls -id .
270443 ./
$ mkdir tmp
$ cd tmp
$ ls -id ..
270443 ../
the -i option to ls makes it give you the inode number of the file. If you were to try this on your system you’d probably get a different number, but the specific value doesn’t matter. It’s just a unique value that identifiles a particular file/directory.
This shows that, when you check the current directory’s inode and then enter a subdirectory and check its parent’s inode, they are the same value. They are hard links to the same bit of data.
But hard links aren’t just for the filesystem. Another important use of hard links are for backing up data. Take an important file and make a backup of it by creating a hard link pointing to it. Then, if you need to update the important file, but don’t want to lose the ‘snapshot’ of data on it, you can just dereference the file, overwrite the filename, and the hard link will continue to point to the same piece of data. Leaving you with a backup that you can store in another partition, keeping that data even safer.
When you delete a file, you are actually removing that hard link from memory and dereferencing the data. A file is considered truly deleted then when all of it’s hard links are gone. That data isn’t gone until finally the computer decides to reuse the memory it spent on it.
Now, soft links.
Soft links act as interactable shortcuts to files. Soft links allow you to jump from the link across the filesystem to the file you want to access or modify. Commands which read or write file contents will access the contents of the target file. rm or mv however, merely deletes the link itself, and not the file it points to or the data contained within. Also, if you move or delete the file a soft link points to, the link will become a hanging link and won’t follow it, or be able to read or write to that file at all. The soft link is stored as just a path to that file, they don’t share an inode at all.
Referring back to the earlier example.
$ mkdir tmp
$ cd temp
$ touch basic.file
$ ln -s basic.file softlink.file
$ ls -i
270470 basic.file 270471 softlink.file
In this example, I created a directory called tmp and created a basic file and a symbolic link to the same file. Calling ls -i reveals the inodes of both files, you can see that they are stored in different values, or different blocks of data.