When I first used
ln I tried using it before reading the documentation. I had assumed that linking was a basic enough operation to make the syntax
ln [source-target] [linkname] all I needed to do. I learned though the common deployment of
ln is otherwise. Since I created enough links, and because I felt the syntax should be basic, I created a script to get this behavior.
Besides a basic syntax that was logical to me, there are a few other reasons why I created the script. To know what they are, it helps to know the basics of linking.
The default/non-optioned use of
ln creates a hard link. A “hard link” is essentially just another name for an existing file. Because the hard link and its source (“target” in the documentation’s wording) share the same file system inode, they are almost indistinguishable (the inode contains all the information about a file).
Hard links are rarely used however. For several reasons its alternative a symbolic link is. While the
ln default behavior does create a hard link, its existence is likely a inherited artifact—hard links came before symbolic links and program syntax had to be maintained to run as the users expected.
A symbolic link is more versatile than a hard link. It is sometimes referred to as a “symlink” or a “soft link” and it has some advantages. It can be:
- readily used on directories
- used across file system boundaries
- created if the source/target doesn’t exist
- color formatted with the
lscommand (and often is by default)
Further explanation of what a symbolic link is (as explained in the
ln Info page, lightly paraphrased):
A symbolic link is a special type of file that refers to a different file by name. Most operations that are passed to the link file (opening, reading, writing…) are deferred by the kernel to operate on its target. Some operations (e.g. removing) work on the link file itself. The owner and group of a symlink have no effect on the file access of the target — they only have an effect on the removing of the symlink itself. On the GNU system, the file mode bits of a symlink have no significance and cannot be changed.
A symlink can be defined either with absolute or relative paths, the later being commonly used on removable media.
cd $HOME touch file.txt ln file.txt file_hrdlink.txt ln -s /home/$USER/file.txt /home/$USER/file_symlink-absolute.txt ln -s ../$USER/file.txt file_symlink-relative.txt ln -s ../$USER/FILE.txt file_symlink-relativebroken.txt
“Dance with the one that brung ya”
A basic syntax was what I wanted to be able to link by and why I created the script, additionally, a couple more benefits were able to be added:
- symbolic links used by default as they are more flexible
- absolute paths used for consistency and because they are usually more inductive to resolve
- existence tests used on the source target and destination directory
lnk [source-target] [directory-or-linkname] — a generic linker
lnk can be found in my general-scripts repository.