Symbolic Links
Inodes
An important concept I learned in my Operating Systems CS class was the abstraction of inodes for the filesystem: a datastructure that contains metadata about a file or directory with pointers (direct, indirect, double indirect) to the underlying data blocks.

One nuance with inodes is the existence of symbolic links and hard links. I remember being really confused about this difference and asking my professor after class. I vaguely remember him explaining to me the details and that symbolic links are often the better choice over hard links. One message that was clear: hard links can be dangerous. However, I never really thought twice about it until recently, when I was trying to set up a git repo for my vim
and tmux
configuration files and saw a recommendation to make symlinks to the dot files (so vim
or tmux
can still find it when looking in root).
Symbolic vs. Hard Links
So what is the difference? I had to do some googling to review it, but this visualization captures it perfectly:

They both function as shortcuts to files and directories, but how they do it is different. A soft or symbolic link is a file that points to another file via storing its file system path string as data (it has a different inode number). When the original file is deleted, the soft link is left dangling. If you create a new file with the same name, the soft link will become active again and attach to that file.
Instead of storing the file path, a hard link points directly to the underlying inode of the original file (it has the same inode number). A good way to think about it is that every file starts with 1 hard link at creation time. The filesystem keeps track of how many hard links point to the inode (there is a hard link counter inside the inode metadata) so when you create another hard link, the counter is incremented. Only when all of the hard links are deleted will the data in the filesystem be freed. This can be dangerous if you lose track of all your hard links, and find that you cannot actually delete the file due to the counter being positive. It is also the case that sym links can cross filesystems while hard links cannot.
Creating Symbolic or Hard Links
In Linux you can create sym links with the command:
ln -s <target> <link_name>
This creates a sym link with link_name
to the source or target
file.
For hard links just omit the -s
flag:
ln <target> <link_name>
So when I run the following command, I can have a symlink in root for vim
, bash
or tmux
that links to the underlying file stored in my dotfiles repo.
# Create a symlink
ln -s ~/dotfiles/vimrc ~/.vimrc
Enjoy Reading This Article?
Here are some more articles you might like to read next: