Friday, January 29, 2010

Hard vs. symbolic links

I don't know why I don't use many hard links.  Habit, I guess. I'll try to break it.

A symbolic link is a special file that points to another file, i.e.

lrwxrwxrwx 1 root root 4 Jun 23  2007 awk -> gawk*

Delete gawk, and awk points nowhere - and won't work.  Delete awk, and nothing at all happens to gawk.

A hard link is simply a file that points to the same inode as another.  In effect, it's just another way of referring to the same file.  You can't tell by looking at it that it's a hard link, and if you delete it - or the file it's linked to - nothing happens to the other file.  The only clue you've got is by looking at the link count, that column in 'ls -l' that nobody knows what it is:

-rwxr-xr-x 3 root root 62872 Jan 14 14:06 gunzip
-rwxr-xr-x 3 root root 62872 Jan 14 14:06 gzip
-rwxr-xr-x 3 root root 62872 Jan 14 14:06 zcat

Each has a link count of 3.  That means that there are three different files sharing the same inode number.  And, sure enough:

[root@dg bin]# ls -i *z*
319701 gunzip  319701 gzip  319701 zcat

So why have three 'identical' files with different names?  Well, here's what I do with one of my scripts.

[root@dg scripts]# ls -lai start*
1357990 -rwxr-xr-x 3 root root 446 Jan 28 16:44 start
1357990 -rwxr-xr-x 3 root root 446 Jan 28 16:44 start_this
1357990 -rwxr-xr-x 3 root root 446 Jan 28 16:44 start_that

Same file, hard linked.

#!/bin/bash

 ECHO="/bin/echo"
 MAIL="/bin/mail"

 CALLED_NAME="`basename $0`"
 case $CALLED_NAME in
    start_this)
        ICDIR="/thisdir"
    ;;
    start_that)
        ICDIR="/thatdir"
    ;;
    *)
        ICDIR="/theotherdir"
    ;;
esac

 cd $ICDIR||{ $ECHO "$0 failed chdir"|$MAIL tim;exit 1; }

/usr/local/bin/icrun

So all I do is see how it's called, and operate accordingly.

I believe that in dg/ux, cp was a hard link to mv.

No comments:

Post a Comment