0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use ln Command in Linux: Create Links Easily

The ln command in Linux creates links between files. Use ln source target for a hard link or ln -s source target for a symbolic (soft) link. Links let you access the same file from different paths without copying it.
📐

Syntax

The basic syntax of the ln command is:

  • ln [options] <source> <target>

Where:

  • source: The original file or directory you want to link to.
  • target: The name of the new link you want to create.
  • options: Flags to modify behavior, like -s for symbolic links.

Without options, ln creates a hard link. With -s, it creates a symbolic link.

bash
ln [options] <source> <target>
💻

Example

This example shows how to create a symbolic link named link_to_file.txt pointing to original_file.txt. The symbolic link acts like a shortcut to the original file.

bash
echo "Hello, world!" > original_file.txt
ln -s original_file.txt link_to_file.txt
cat link_to_file.txt
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when using ln include:

  • Forgetting the -s option when you want a symbolic link, which creates a hard link instead.
  • Creating links to directories without -s, which is not allowed for hard links.
  • Using relative paths incorrectly, causing broken links.

Always check if you need a hard or symbolic link and verify paths carefully.

bash
ln original_file.txt link_hard
ln -s original_file.txt link_soft
ls -l link_hard link_soft
Output
lrwxrwxrwx 1 user user 17 Apr 27 12:00 link_soft -> original_file.txt -rw-r--r-- 2 user user 14 Apr 27 12:00 link_hard
📊

Quick Reference

OptionDescription
-sCreate a symbolic (soft) link
-fForce removal of existing destination files
-nDo not dereference destination if it is a symlink
-vVerbose output showing actions
--helpShow help message

Key Takeaways

Use ln -s source target to create symbolic links, which are like shortcuts.
Hard links share the same data but cannot link directories; symbolic links can link directories.
Always verify paths to avoid broken links, especially with symbolic links.
Use ls -l to check if a link is symbolic (shows ->) or hard (same inode).