4

I use symbolic links quite often, but after moving the original file, I lose track of the symbolic link. I also use symbolic links for keeping track of some files in the same directory, but again, I lose track.

  • Is there any way (tool/method) to keep track of the symbolic link no matter what change I make? Is the hard link the only way for this?
  • Is there any way to make the symbolic link in a relative way so that when I move the directory that contains both the original and link, the link should work.

2 Answers 2

7

Concering your second question, if you make the symlink using a relative path and then move the whole directory structure, it still should work. Consider the following terminal session:

~$ mkdir test
~$ cd test/
~/test$ mkdir test2
~/test$ cd test2/
~/test/test2$ touch testfile; echo "hello, world" > testfile
~/test/test2$ cat testfile 
hello, world
~/test/test2$ cd ..
~/test$ ln -s ./test2/testfile testfileln
~/test$ ls -l
total 8
drwxr-xr-x 2 xxxx xxxx 4096 2010-09-09 09:18 test2
lrwxrwxrwx 1 xxxx xxxx   16 2010-09-09 09:18 testfileln -> ./test2/testfile
~/test$ cd ..
~$ mv test/ testfoo
~$ cd testfoo/
~/testfoo$ ls -l
total 8
drwxr-xr-x 2 xxxx xxxx 4096 2010-09-09 09:18 test2
lrwxrwxrwx 1 xxxx xxxx   16 2010-09-09 09:18 testfileln -> ./test2/testfile
/testfoo$ cat testfileln 
hello, world

As for your first question, if you really want a link that will refer to the same file no matter what you do with the original location of the file, a hard link is probably what you want. A hard link is basically just another name refering to the same inode. Thus, there is no difference between the hard link and the "original file." However, if you need to link across file systems, hard links often do not work and you usually cannot make hard links to directories. Further, you will notice some differences when performing some file operations. Most notably, removing the original will not remove the file. The hard link will still point to the file and be accessible.

1
  • Moreover, about hard links, you can only use them for plain files, not directories (unless you work with latest HFS+ filesystem)
    – mouviciel
    Sep 10, 2010 at 15:10
2

You can use the readlink command to discover/check what a (now broken) link originally pointed to and then fix it up to point to whatever the file's new name/location is. Or you could do your file renaming only through a shell script that renames a file and searches for and fixes any links that point to it. Either way, you would so something like this:

find . -type l | while read L
do
    if readlink $L | grep -q "^$OLDNAME\$"
    then
        ln -sf $NEWNAME $L
    fi
done

However, if you're doing this all the time then symlinks are probably not what you should be using.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .