Search code examples
bashrelative-pathsymlink

Symlinks not working when link is made in another directory?


Wow, I've never really used symlinks that much before, but this is really boggling:

bash-3.2$ echo "weird" > original.txt
bash-3.2$ mkdir originals
bash-3.2$ mv original.txt originals/
bash-3.2$ cat originals/original.txt 
weird
bash-3.2$ mkdir copies
bash-3.2$ ln -s originals/original.txt copies/copy.txt
bash-3.2$ cat copies/copy.txt 
cat: copies/copy.txt: No such file or directory
bash-3.2$ ls copies/copy.txt 
copies/copy.txt
bash-3.2$ ls -l copies/copy.txt 
lrwxr-xr-x  1 zach  staff  22 Dec 22 01:23 copies/copy.txt -> originals/original.txt
bash-3.2$ cat originals/original.txt 
weird
bash-3.2$ cat copies/copy.txt 
cat: copies/copy.txt: No such file or directory
bash-3.2$ cd copies/
bash-3.2$ cat copy.txt 
cat: copy.txt: No such file or directory

Why can't I cat the symlink in the copies directory?

If I make the symlink from inside the copies/, I can cat it just fine. If I make the symlink in the current directory, I can also cat it just fine. If I make the symlink in the current directory and then move it to copies/, I get "copies/copy.txt: No such file or directory".


Solution

  • If you create a relative path to a symbolic link, it will store it as a relative symbolic link. Symbolic links are relative to the location the link is in, not the location where it was created or opened.


    Please use absolute path or path relative to the link.

    Change:

    ln -s originals/original.txt copies/copy.txt
    

    To:

    # absolute
    ln -s /path/to/originals/original.txt copies/copy.txt
    
    # relative
    cd copies
    ln -s ../originals/original.txt copy.txt