Saturday, January 8, 2011

Link Files in Unix/Linux

Links in Unix - Links are used in Unix/Linux for better managebility of file system.

Command we use for linking two files is ln.

ln -[options] existingfilename newfilename

Common options -

-f ---> Link files without questioning the user, even if the mode of target forbids writing.
-s ---> Creates a symbolic link to existingfilename with the name of the newfilename.

Hard Link - A hard link is a reference to a file or directory that appears just like a file or directory, not a link. Hard links only work within a filesystem. In other words, don’t use hard links between mounted filesystems. A hard link is only a reference to the original file, not a copy of the file. Basically points to a file's inode. So if you delete one file , it can still be accessed from other hard link available.

How do we check hard links -
If we want to check hard links in one specific directory we can simple use ls -i command which list the files with their respective inode number.

If we want to find all files hard linked with one file we can use find command in following way -
find {location} -xdev -samefile {filename}

ls -lrt shows the number of links to a file. The column next to permissions shows number of links to that file.


Soft Link - A soft link/symbolic link is a pointer to another file or directory. It can be used just like the original file or directory. A symbolic link appears in a long listing (ls -l) with a reference to the original file/directory. A symbolic link, as opposed to a hard link, is required when linking from one filesystem to another and can be used within a filesystem as well.

How to find soft links -
If we do ls -lrt in one directory it shows the soft links with target files.
Find all links in system - find {location} -type l


How to unlink files -

unlink filename

PS: unlink and rm both remove the files, the difference is that unlink is a system call, rm is a shell utility that calls unlink.

Keep checking for more posts on Unix/Linux

2 comments:

  1. Nice one dude, this is the most common asked question in any unix interview and its also one of most useful unix commands

    I also find useful command "ln -nsf sourcefinle linkname" to update any soft link which I used most.

    Cheers
    Javin
    FIX Protocol tutorial

    ReplyDelete
  2. Thanks dude..
    I am following your blog to learn FIX these days. Nice attempt.

    keep in touch.
    Cheers

    ReplyDelete