Symbolic links (also called symlinks or soft links) act as shortcuts to other files or directories on Linux. Usually, they are just used as a matter of convenience. Sometimes, they’re also used to create links to files whose paths frequently change. For example, it’s easier to update a single symlink than it is to update 10 Bash scripts with the new location of a file that they all use.
In this tutorial, you will learn how to create and delete symbolic links in Linux. We’ll also cover some important things to keep in mind about the capabilities and limitations of symlinks.
Creating a Symlink
Step 1. We’ll use the
ln (link) command below to create a symbolic link to a file. The
-s option tells the command to make the link symbolic. For the first argument, specify the path to file or directory you want to link to. The second argument will contain the path to your symlink.
$ ln -s /home/linuxnightly/myfile /opt/mylink
The command above creates a symlink at
/opt/mylink, which will link to
/home/linuxnightly/myfile. No output means that the link was created successfully.
Step 2. The file can now be accessed through the symbolic link. Let’s test.
$ cat /opt/mylink Hello world!
Step 3. We can use the
ls command to view details about the symbolic link and see which file it references.
$ ls -l /opt/mylink lrwxrwxrwx 1 root root 25 Oct 11 18:14 /opt/mylink -> /home/linuxnightly/myfile
l at the beginning of the line also tells us that this file is a symbolic link.
Delete a Symlink
There are two ways to delete a symbolic link. Either with the
$ unlink /opt/mylink
$ rm /opt/mylink
Overwrite a Symlink
If you need to change the file or directory that a symbolic links refers, you don’t need to delete it and create a new one. Instead, use the
-sf option to overwrite the symlink.
$ ln -sf /root/myfile /opt/mylink
You Should Know…
Here are some facts you should keep in mind about symbolic links and how they work on Linux.
- If the path to your file or symlink contains a space, you can wrap them in quotes
" "so it will work
- You can use absolute or relative paths in your symlink syntax. The better option will depend on the scenario
- If the original file gets moved or deleted, the symlink will remain but be in a broken state
- A symbolic link has
777permissions but it doesn’t affect the actual permissions of the file it refereces