How To Create Symbolic Links In Linux Using Ln Command

"ln" command is used in Linux to create the symbolic links. Symbolic links are great way to save your disk space. If the data is needed in multiple places/directories, rather than duplicating the data, one can create link to data and access it from his/her current directory.

Lets first see, how we can create symbolic or symlink to a file. Also check how to check if symlink to file exists in bash.

How to create symlink to a file in Linux


Where FILE is to which we want to create a LINK

ex: lets create a file call test.txt in tmp directory and create a link to this file in the home directory...

➜ /home pwd

We are in home directory. Lets create a empty file test.txt in tmp directory with touch command.

➜ /home touch /tmp/test.txt

Lets create a symlink to /tmp/test.txt in the home directory.

➜ /home ln -s /tmp/test.txt .

Ok Now we have created the link. Lets check with ls -lrt command.

➜ /home ls -lrt test.txt
lrwxrwxrwx 1 root root 13 Oct 24 05:00 test.txt -> /tmp/test.txt

As we see above the link in home directory has been created.

If the file test.txt link already exists in your home directory then you use -f (force) switch to do that.


➜ /home ln -s /tmp/test.txt .
ln: failed to create symbolic link ‘./test.txt’: File exists
ln -sf /tmp/test.txt .

To remove the link, Use rm command...

rm test.txt

How to create symlink to a directory in Linux

Lets go through a similar example. Lets create a test directory testdir in /tmp/ directory and create a symlink in the home directory.

➜ /home mkdir /tmp/testdir

Ok the directory has been created in the /tmp/ directory. Lets create the symlink to this directory using the ln command.

➜ /home ln -s /tmp/testdir .

We can check if the link is created, using the ls -lrt command.

➜ /home ls -lrt testdir
lrwxrwxrwx 1 root root 12 Dec 17 00:14 testdir -> /tmp/testdir

Yes indeed the link "testdir" exists now in /home directory which is pointing to /tmp/testdir.

We can remove the link using rm command. Lets try that without the -f switch.

➜ /home rm testdir
rm: remove symbolic link ‘testdir’? y

It is asking us yes or no before removing the link. Press y if you want to remove the link. Lets check if the link still exists.

➜ /home ls -lrt testdir
ls: cannot access testdir: No such file or directory

Ok the link has been removed. Checkout also how to check if symlink to a directory exits in bash.