The Linux operating system is one of the most amazingly flexible systems available. One tool that helps to make Linux so flexible is the "ln" command. The "ln" command allows the user to create links from one file to another. This Linux Command Line series entry will show you how to use ln.
What are links?
A link is basically a pointer that links two files - one to the other. This gets a bit confusing because one of those endpoints isn't really a file, it's a link. For example: You have a file in /data called reports which is a large database that you want all of your users to be able to use. Instead of having to copy that file to each users' home directory, and then go through the trouble of making sure each user updates the original file when they are finished working, you would create a link from their home directories to the reports file. With each user having a symbolic link to the same file, when they update the file it will be reflected in the original. Of course this can cause problems if more than one user is working on the file at a time and one save can overwrite anothers' work.
Hard links vs. Soft links
There are two kinds of links: Hard and soft (or sym) links. They are very similar to one another, but the variations make them quite different. Here are the specifications for each:
- Is a pointer to a file or program but NOT a directory.
- If the linked file is moved or destroyed, the link is not broken.
- Hard links can NOT span from one drive to another.
- Is a pointer to a file, program, or directory.
- If the linked file is moved or destroyed, the link is broken.
- Soft links CAN span from one drive to another.
How do you create links?
Creating links is done with the ln command. Say you want to create a link to the reports database on the /data directory. To create a hard link to this directory, enter the command (from within the directory you want the link to be):
Now, let's suppose that database is on a different drive. For this you need to create a soft link (or symlink) like so:
ln -s /data/reports
Remove links with the standard Linux rm command like:
The above command would remove only the link created in your home directory. Any time you use that file, when you save data, the saved data would be immediately reflected in the original file that you linked to.
Although they seem complex, links are actually quite easy to use. The most complex issue is knowing when to use what type of link. Once you have that mastered, you'll be using links like a pro.