Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symlinks not working when link is made in another directory?

Tags:

bash

symlink

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".

like image 270
user225643 Avatar asked Dec 22 '11 09:12

user225643


People also ask

How do I create a symbolic link from one directory to another?

Ln Command to Create Symbolic Links By default, the ln command creates a hard link. Use the -s option to create a soft (symbolic) link. The -f option will force the command to overwrite a file that already exists. Source is the file or directory being linked to.

Why are my symbolic links broken?

A symlink is broken (or left dangling) when the file at which it points is deleted or moved to another location. If an application's uninstallation routine doesn't work properly, or is interrupted before it completes, you might be left with broken symlinks.

Can symbolic links link directories?

Symbolic links allow you to access specific files or directories from your current location, which is similar to how we use desktop shortcuts.

How do I fix a broken symbolic link?

The only way to fix these broken symlinks is by deleting them. Your system contains hundreds of dangling links and no one has the time to check for these links manually. In such cases, Linux tools and commands prove to be really helpful.


1 Answers

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
like image 97
kev Avatar answered Sep 18 '22 08:09

kev