Common Software

Using Symbolic and Hard Links

Instead of copying files and directories to different parts of the file system, links can be set up to access that same file from multiple locations. Linux supports both soft links (usually called symbolic links) and hard links.

 

When you try to open a symbolic link which points to a file or change to one that points to a directory, the command you run acts on the file or directory that is the target of that link. The target has its own set of permissions and ownership that you cannot see from the symbolic link. The symbolic link can exist on a different disk partition than the target. In fact, the symbolic link can exist, even if the target doesn’t.
A hard link can only be used on files (not directories) and is basically a way of giving multiple names to the same physical file. Every physical file has at least one hard link, which is commonly thought of as the file itself. Any additional names (hard links) that point to that single physical file must be on the same partition as the original target file (in fact, one way to tell that files are hard links is that they all have the same inode number). Changing permissions, ownership, date/time stamps, or content of any hard link to a file results in all others being changed as well. However, deleting one link will not remove the file; it will continue to exist until the last link to the file is deleted.
Here are some examples of using the ln command to create hard and symbolic links:

 

$ touch myfile
$ ln myfile myfile-hardlink
$ ln -s myfile myfile-symlink
$ ls -li myfile*
292007 -rw-rw-r– 3 francois francois 0 Mar 25 00:07 myfile
292007 -rw-rw-r– 3 francois francois 0 Mar 25 00:07 myfile-hardlink
292008 lrwxrwxrwx 2 francois francois 6 Mar 25 00:09 myfile-symlink

Notice that after creating the hard and symbolic link files, we used the ls -li command to list the results. The -li option shows the inodes associated with each file. You can see that myfile and myfile-hardlink both have the inode number of 292007 (signifying the exact same file on the hard disk). The myfile-symlink symbolic link has a different inode number. And although the hard link simply appears as a file (-), the symbolic link is identified as a link (l) with wide-open permissions. You won’t know if you can access the file the symbolic link points to until you try it or list the link target.

This article was copied from the book: Fedora Linux Toolbox: 1000+ Commands for Fedora, CentOS and Red Hat Power Users

I hope the guys who wrote the book won’t mind that I used the information here.

Leave a Reply