Links Between Files
There are two ways to create pointers to files or directories in the file system: by creating a hard link to the file or by creating a symbolic link (also known as soft link) to the file. Each kind has its advantages and disadvantages.
Each file starts with a single hard link, from its initial name to the data in the file system. When you create a new hard link to a file, you create another name that points to that same data. The new hard link acts exactly the same as the name of the original file. Once created, you cannot tell the difference between the new hard link and the original file name.
You can use the ln command to create a new hard link (another name) that points to an existing file. The command needs at least two arguments, a path to the existing file and the path to the hard link you want to create.
In the example avobe it is created a new hard link named newhlink in the tmp directory, for the original file named existingfile.
If the original file is deleted, the file content remains available as long as there is at least one hard link. Data is only removed from storage when the last hard link is removed.
Limitations of hard links:
- Hard links can only be used with normal files. You cannot use ln to create a hard link to a special directory or file.
- Hard links can only be used if both files are on the same file system.
A symbolic link is not a regular file, but a special file type that points to an existing file or directory.
The ln -s command allows you to create a symbolic link:
In the example avobe it is created a new symbolic link named newsoftlink for the original file named originalfile.
When the original regular file is deleted, the soft link will still point to the file, but the destination disappears. A soft link that points to a missing file is called a dangling link.
Soft links have some advantages compared to hard links:
- They can link two files on different file systems.
- They can point to a directory or special file, not just a regular file