Make a symlink in bash with two relative paths

Solution 1:

You can do either of

  1. Use absolute paths

    $ ln -s ~/dir1/file.txt ~/dir2
    $ readlink dir2/file.txt 
    /home/terdon/dir1/file.txt
    
  2. Use the right relative paths

    $ ln -s ../dir1/file.txt dir2/
    $ readlink dir2/file.txt 
    ../dir1/file.txt
    

Depending on your use case, one may be better than the other. Just remember that when creating links using relative paths, the paths must be relative to the target and not to your current location.

Solution 2:

Your question is kinda confusing.

  1. You asked "Is there any way that I can make a symlink to it from ~/dir1 [...] ?" I suppose you meant "from ~/dir2", based on the rest of your post?

  2. Your first command

    $ ln -s ./dir1/file.txt ./dir2/file.txt

    does not do what you think it does. Assuming you're still in your home directory, the above command creates a symlink whose own path is ~/dir2/file.txt, and this symlink points literally to the path ./dir1/file.txt. Because said symlink resides in the directory ~/dir2, such target path resolves to ~/dir2/./dir1/file.txt, which further resolves to ~/dir2/dir1/file.txt (probably non-existent and not what you want). So I doubt why you said it resolves to ~/dir1/dir2/file.txt.

  3. Your 2nd command fails because there's no directory ../dir2 to put the symlink in, and that's what the error message meant.

  4. To answer your question, yes. The OS doesn't care whether your symlink points to a path with no valid filesystem object present.

Probably what you really want is something like

ln -s ../dir1/file.txt ./dir2/file.txt

I guess? This command creates a symlink whose own path is ./dir2/file.txt, and its target is the literal relative path ../dir1/file.txt. The final, absolute path pointed to by the symlink is ~/dir2/../dir1/file.txt, which resolves to ~/dir1/file.txt.

Note that the ~ symbol is a shell expandable character which expands to the absolute path of your home directory. ~-expansion is not part of OS path resolution.

Suggested reading

Linux manpages of path_resolution(7), symlink(7), ln(1) and ln(1p).

Edit

Clarifications & suggested reading.