1. Overview

In this tutorial, we’ll be discussing the different ways in which we can make symbolic links in Linux. They’re also called soft links, and together with hard links, we can create them using the ln command.

Make sure to take a look at our introduction to soft and hard links before diving into this one.

Note that the examples in this article use commands that are tested in Bash and should work in all POSIX-compatible shells.

We can think of ln as coming in four forms.

The first form requires us to be explicit in naming both the target and the link we want to create:

ln -s file.txt link.txt

With this command, we have created a symbolic link called link.txt that points to the file.txt file. Using the command ls -l, we can see the result:

-rw-rw-r--. 1 vagrant vagrant 10 Apr 12 15:23 file.txt
lrwxrwxrwx. 1 vagrant vagrant  8 Apr 12 15:23 link.txt -> file.txt

We can create symlinks to directories in the same way:

ln -s dir link

This applies to the other forms as well.

Of all the forms, this is the only form in which we can create links to files located in the same directory. This becomes clear when we look at the second form.

This second is the shortest of all four forms. By omitting the link name, ln will create links in the current working directory that have the same name as the target. 

For example, we can create a link called log in our current directory that points to /var/log with the following command:

ln -s /var/log

Our link will look something like this:

lrwxrwxrwx. 1 vagrant vagrant 8 Apr 12 15:35 log -> /var/log

Note that this command won’t work if we execute it from within the /var directory. Let’s cd into /var and try again:

cd /var/
ln -s /var/log

Our system will complain that the file already exists:

ln: failed to create symbolic link ‘./log’: File exists

The remaining two forms are all about creating multiple links at once.

Let’s link a file and directory in one statement:

ln -s /etc/hosts /var/log /home/vagrant

With this command, we have created two links, respectively pointing to a file and a directory. They are located in the target directory, in this case, /home/vagrant:

lrwxrwxrwx. 1 vagrant vagrant 10 Apr 12 15:50 hosts -> /etc/hosts
lrwxrwxrwx. 1 vagrant vagrant  8 Apr 12 15:50 log -> /var/log

The fourth form is very similar to the third. The only difference is that we now first state the directory where to create the links by using the -t parameter:

ln -s -t /home/vagrant /etc/hosts /var/log

The result is the same as if we had used the third form:

lrwxrwxrwx. 1 vagrant vagrant 10 Apr 12 15:50 hosts -> /etc/hosts
lrwxrwxrwx. 1 vagrant vagrant  8 Apr 12 15:50 log -> /var/log

6. Conclusion

As we have learned, there are four forms in which we can use ln to create symbolic links.

Of all forms, the first one is the most explicit and the only form that allows linking to files or directories in the same location.

Comments are closed on this article!