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.

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:

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:

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, if you're in your home directory:

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

Important note about relative paths in symbolic links:

For Example:

If you are in a parent directory and within that directory you have two folders named dir1 and dir2. Inside of dir1 you have a source file, we will call it source.txt. To create a symbolic link located in dir2 that uses dir1/source.txt as its source you would do:

ln -s ../dir1/source.txt dir2/symlink

Because our symbolic link is in dir2 the path to the source file is ../ that get us out of dir2, then we go into dir1 where we find source.txt

You could also use and absolute path to 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