ln
Command: Creating Links in Linux
Summary
The ln
command in Linux is used to create links between files. It allows you to access the same file through multiple names, either as hard links or symbolic (soft) links. This post will cover the usage of ln
, provide examples, and explain the commonly used flags.
Introduction
The ln
command is a fundamental utility in Linux for creating links, which are essentially pointers to files. There are two types of links:
- Hard Links: A hard link creates a new directory entry that points to the same inode as the original file. This means that the link shares the same data blocks on the disk. If you modify the file through one link, the changes are reflected in all other hard links. Deleting the original file does not delete the data as long as at least one hard link remains. Hard links cannot cross file system boundaries and cannot be created for directories (typically).
- Symbolic (Soft) Links: A symbolic link creates a new file that contains a string pointing to the location of the original file (the target). It's like a shortcut. If the original file is deleted or moved, the symbolic link will become broken. Symbolic links can cross file system boundaries and can link to directories.
Use case and Examples
Creating a Hard Link
This creates a hard link namedhard_link
that points to original_file
. Any changes made to either file will be reflected in both. Creating a Symbolic (Soft) Link
This creates a symbolic link namedsymbolic_link
that points to original_file
. The -s
option is crucial for creating symbolic links. Linking a Directory (Symbolic Link Required)
You must use-s
to create a symbolic link to a directory. Hard links to directories are generally not allowed. Verifying the Link
This will display the details of the original file and the created links. For symbolic links, you will see the link pointing to the target file. Hard links will have the same inode number.Demonstrating Hard Link Behavior
This demonstrates that changes made through the hard link are reflected in the original file.Demonstrating Symbolic Link Behavior after Deletion
This demonstrates that a symbolic link becomes broken if the original file is removed.Commonly used flags
Flag | Description | Example |
---|---|---|
-s | Create a symbolic link (soft link). | ln -s original_file symbolic_link |
-f or --force | Force creation of the link, even if a file with the same name already exists. This will overwrite the existing file. | ln -sf original_file existing_link |
-n or --no-dereference | Treat the destination as a normal file, even if it is a symbolic link. When creating hard links, this is the default. When creating symbolic links, overwrite destination that is a symlink. | ln -n original_file existing_symlink |
-v or --verbose | Print the name of each linked file. | ln -sv original_file symbolic_link |
-i or --interactive | Prompt the user whether to overwrite destination files. | ln -i original_file existing_file |