
What is the difference between a hard link and a symbolic link?
One fairly common task in a programming interview is to elucidate the difference between a hard link and a symbolic link to a file. It’s an interesting question, not least because not all are clear on the advantages of symbolic links. When you make a a file and call it f1.txt, as you see in the diagram above, your computer creates a link that takes you directly to the place in memory where your data is stored. That’s a hard link. So what’s a symbolic link, and why mess with it?
A symbolic link is essentially a meta-link: it’s a link to a link. If you create a link to f1.txt called f2.txt, as seen above, you are asking f2.txt to store a path that will eventually take you to your file, f1.txt.
This has several advantages. Symbolic links can be used to point to directories, whereas hard links cannot. Symbolic links are also portable across computers. If I have a code that references f2.txt, as above, it will look for an f1.txt regardless of the computer I run the code on. So if every member of your team has an important file f1.txt, but they have perhaps messed with the file on their own computers, your symbolic link won’t care. The code will run on everyone’s computers, using their own versions of f1.txt.
Symbolic links can also function faster than hard links in certain circumstances. Many of the attributes of your f1.txt are stored in the hard link, which can make the hard link slow to load if you change f1.txt often. A symbolic link would not track these changes, and could actually access your file faster.
That said, hard links are usually faster! A symbolic link essentially adds another step: instead of linking to a place in memory, you link to a link to a place in memory. But when pointing to a directory, a frequently-changing file, and/or a file that may have multiple versions on multiple computers, they can smooth out your development nicely.