Links

The ln Command

This command creates either hard links or soft (sym) links; soft links are similar to Windows shortcuts.

Hard links are a new concept to Windows users; they effectively put the exact same file in more than one location. Symlinks are very similar (but not identical) to shortcuts. By default, the ln command creates hard links.

 

Create a hard link

First, create a simple file to work with:

touch myfile

You create a link with a command like this:

ln myfile mytestlink

The syntax is:

ln target_of_link link_file_name

 

So you choose a target file (like your file “myfile” above) and then a location for the hard link (in this case, your home directory, with the name “mytestlink”).

Run ls -la and note the relationship of these two files.

 

Nothing Prevents A File From Being Listed In Two Different Directories
(or even twice in one directory)

With the above concepts clearly in mind, now think of a file that appears in two different directories. What the directory listing is really referring to is an inode. There are not two copies of the file; there is only one. It just shows up in two different places.

You can verify this by creating a link, then using the -i option to the ls command:

touch myfile

ln ./myfile ./myfile2

ln -li

In this listing, note the inode number on the left. Both myfile and myfile2 have the same inode.

 

Can You Hard Link Directories?

Normal users can’t. Root can. But it’s a terrible idea, and is very rarely done.

 

There are also “soft” links, or symlinks

Symlinks are somewhat similar to Windows shortcuts.

Most actions are passed through the link to the target, i.e. opening a program.

Only creation and deletion actually act on the link file itself.

 

Create a Soft Link

With a command like this:

ln -s myfile mysoftlink

The syntax is:

ls -s target_of_link link_file_name

 

Note the -s option, which makes ln create a soft link (symlink) rather than a hard link.

 

Can You Soft Link Directories?

Absolutely. This is commonly done to simplify navigation:

ln -s /var/tmp /usr/tmp

NOTE that deleting a file to which there are hard links will only delete the file in the current directory. Other “copies” of the file still exist elsewhere (everywhere it’s linked).

 

Deleting a file to which there are symlinks does NOT delete those symlinks (which is the same thing that happens in Windows).