Directory – Create Symbolic Link Relative to Current Directory

directorylnsymlink

I'm trying to create a symbolic link in my home directory that points to a directory on my external HDD.

It works fine when I specify it like this:

cd ~
ln -s /run/media/name/exhdd/Data/ Data

However it creates a faulty link when I try this:

cd /run/media/name/exhdd
ln -s Data/ ~/Data

This creates a link that I cannot cd into.

When I try, bash complains:

bash: cd: Data: Too many levels of symbolic links

The Data symbolic link in my home is also colored in red when ls is set to display colored output.

Why is this happening? How can I create a link in that manner? (I want to create a symlink to a directory in my working directory in another directory.)


Edit: according to this StackOverflow answer, if the second argument (in my case that'd be ~/Data) already exists and is a directory, ln will create a symlink to the target inside that directory.

However, I'm experiencing the same issue with:

ln -s Data/ ~/

Best Answer

Here's what's happening. If you make a symlink with a relative path, the symlink will be relative. Symlinks just store the paths that you give them. They never resolve paths to full paths. Running

$ pwd
/usr/bin
$ ln -s ls /usr/bin/ls2

creates a symlink named ls2 in /usr/bin to ls(viz. /usr/bin/ls) relative to the directory that the symlink is in (/usr/bin). The above command would create a functional symlink from any directory.

$ pwd
/home/me
$ ln -s ls /usr/bin/ls2

If you moved the symlink to a different directory, it would cease to point to the file at /usr/bin/ls.

You are making a symlink that points to Data, and naming it Data. It is pointing to itself. You have to make a symlink with the absolute path of the directory.

ln -s "$(realpath Data)" ~/Data