How to create a link to an existing file or directory using a GNU Linux shell command?
You can create a link in GNU/Linux with the ln
command. There are two main types of links:
-
Hard Link
- Points directly to the same data on disk as the original file.
- Both names share identical inode information, so deleting one name does not remove the actual data if the other still exists.
- Cannot link directories with a hard link (except in unusual circumstances or with special filesystem support).
ln /path/to/original_file /path/to/hard_link
-
Symbolic Link (Soft Link)
- Stores a reference (path) to the target file or directory.
- Deleting the original file breaks the symlink.
- Can link directories this way (and files too).
ln -s /path/to/original /path/to/symlink
-s
: Indicates creation of a symbolic (soft) link.
Examples
-
Linking a File
# Hard link ln myfile.txt myfile_link.txt # Symbolic link ln -s myfile.txt myfile_symlink.txt
-
Linking a Directory
Hard links to directories are typically unsupported on most filesystems, but a symbolic link works fine:ln -s /path/to/original_dir /path/to/dir_symlink
-
Overwriting Existing Links
If a link with the same name already exists, you can use-f
to force overwriting:ln -sf /new/target /existing/symlink_name
-
Relative vs. Absolute Paths
- Using absolute paths (
/full/path/...
) ensures the link remains valid even if you move your symlink’s parent folder around. - Using relative paths is useful if you keep both items in the same directory or a known structure and want the link to remain valid if the entire folder is moved together.
- Using absolute paths (
Recommended Resource
To hone your overall engineering skills (beyond just linking files in Linux), consider this course from DesignGurus.io:
- Grokking Data Structures & Algorithms for Coding Interviews
Strengthening your algorithmic knowledge helps you approach complex tasks—whether working with files, directories, or building large-scale software systems—with increased efficiency and clarity.
CONTRIBUTOR
TechGrind