How do I create a relative symbolic link in Linux?

I need a symlink that resolves relative to the directory it is placed in. What command is used to create such a thing?


  1. Go to the directory you want the link to reside in
  2. Run the command ln -s ../some/other/file linkname

The path you provide is stored with the file. When you access the file the stored path is looked up and expanded relative to the file. It does not know what directory you were in when you created the link.


Recent versions of GNU coreutils' ln (>= 8.16) support the --relative (or -r) option which means you can call ln -s with 2 absolute or relative (in respect to your working directory) paths and it will figure out the correct relative path that has to be written to the symlink.


What you need to understand is basically that a symlink is more like a text file than like a directory entry which contains a file. So if you

echo ../poo >/file/name

then that is quite similar to

ln -s ../poo /file/name

The system doesn't care if /file/../poo exists at all, it's just a piece of text which gets put into the symlink. When something tries to open the symlink, that's when the system tries to resolve it.

If you are using a shell with file name completion, this feature can confuse things by allowing you to complete a file name relative to your current working directory, even if you then end up using that as the target of a symlink in completely another directory.


I just wanted to further explain how to create a symlink using relative paths (with a detailed example).

As Ignacio Vazquez-Abrams mentioned in the comments, you must specify the file/folder location relative to where the symlink will be created, not relative to your current directory.

EXAMPLE

You are in /usr/share/nginx/html/_src/learn You will create a symlink coding in /usr/share/nginx/html

Create relative symlink(theory):

sudo ln -s /path/to/source/file-or-folder/relative/from/symlink /path/to/symlink/relative/to/current/location

Create actual relative symlink:

sudo ln -s ./_src/learn/coding ../../coding

More information (same example)

current path:                                  /usr/share/nginx/html/_src/learn
symlink(to be) relative to current path:       ../../coding                 
symlink location (absolute):                   /usr/share/nginx/html/coding
folder/file relative to symlink location:      ./_src/learn/coding
folder/file absolute path:                     /usr/share/nginx/html/_src/learn/coding