CIS120 Linux Fundamentals by Scott Shaper

Creating Symbolic and Hard Links

Think of links in Linux like shortcuts on your desktop, but more powerful. They let you access the same file from different locations without making copies. There are two types: hard links and symbolic (soft) links.

The examples below use the course setup. Work in ~/playground/chapter2 where the setup has created notes.txt and other files you can link to. Use cd ~/playground/chapter2 before trying the commands.

Why Use Links?

Links are useful when you want to:

Hard Links

A hard link is like having multiple names for the same file. Think of it as a person with a nickname - both names refer to the same person. When you create a hard link, both the original file and the link point to the same data on your hard drive.

How Hard Links Work

In Linux, every file has an inode number - a unique identifier that points to the actual data on the disk. When you create a hard link:

Creating a Hard Link

ln original_file link_name

For example, from ~/playground/chapter2:

cd ~/playground/chapter2
ln notes.txt notes_backup.txt

Important Things to Know About Hard Links

Symbolic Links (Soft Links)

A symbolic link is like a shortcut on your desktop. It points to the original file's location. If you move or delete the original file, the link stops working.

Creating a Symbolic Link

ln -s original_file link_name

For example, from ~/playground/chapter2:

cd ~/playground/chapter2
ln -s notes.txt notes_shortcut.txt

Important Things to Know About Symbolic Links

Understanding Paths

When creating links, you need to understand two types of paths:

Absolute Paths

These start from the root directory (/) and show the complete path:

ln -s /home/user/documents/file.txt /home/user/desktop/file_link.txt

Relative Paths

These are based on your current location. For example, from ~/playground/chapter2 with a documents folder:

cd ~/playground/chapter2
ln -s notes.txt documents/notes_link.txt

Important note about relative paths in symbolic links:

For Example:

The course setup creates dir1 and dir2 in ~/playground/chapter2, with source.txt inside dir1. From ~/playground/chapter2 (the parent of dir1 and dir2), to create a symbolic link in dir2 that points to dir1/source.txt, run:

cd ~/playground/chapter2
ln -s ../dir1/source.txt dir2/symlink

Because the symbolic link lives in dir2, the path to the source file must be relative to dir2: ../ goes up to the parent (chapter2), then dir1/source.txt finds the file.

You could also use an absolute path for both the source file and the symbolic link.

What Happens When Source Files Are Deleted

Hard links and symbolic links behave very differently when the original file is deleted:

Tips for Success

Common Mistakes to Avoid