Wednesday, 13 July 2011

Linux - Symbolic Links

With Unix/Linux you can create links to directories/files using a symbolic link. A symbolic link is different to a hard link.

Hard Link vs. Symbolic Link

  • A hard link cannot link to a directory or different filesystem/volume, and must link to an existing file.
  • A symbolic link can link to a directory, different filesystem/volume, and can also link to an arbitary value that may not exist.

Create a hard link

To create a hard link you can issue the following from the command line:
$ ln source_file link_name
This creates the link from source_file to link_name. The first file is always the name of the file you want to create a link to. The second file is always the name of the link that you wish to create.

Create a symbolic link

A symbolic link is created in much the same way, however we issue the -s flag.
$ ln -s source_file link_name

Flags

-f, --force
remove existing destination files
-n, --no-dereference
treat destination that is a symlink to a directory as if it were a normal file

Example of hard link vs symbolic link when removing source file

Hard link:

To test the different between a hard link and a symbolic link I performed the following:

Create a hard link of a test source file:
$ cat test_source
This is the source test file
$ ln test_source test_link
Check the hard link works
$ cat test_link
This is the source test file
Remove the source file
$ rm test_source
Check if the link file still exists
$ ls -ltr
total 40
-rw-r--r-- 1 krobbe dba 29 Jul 6 10:31 test_link
$ cat test_link
This is the source test file
Result: the link file still contains the information that was in the source file even though the source file has been removed.

Symbolic link:

Create soft link:
$ ln -s test_link test_link2
Check the soft link works correctly
$ cat test_link2
This is the source test file
$ ls -ltr
-rw-r--r-- 1 krobbe dba 29 Jul 6 10:31 test_link
lrwxrwxrwx 1 krobbe dba 9 Jul 6 10:34 test_link2 -> test_link
Remove the source file
$ rm test_link
Check the status of the link
$ ls -ltr
total 36
lrwxrwxrwx 1 krobbe dba 9 Jul 6 10:34 test_link2 -> test_link
$ cat test_link
cat: test_link: No such file or directory
Result: The symbolic link is highlighted as there being an error and when we go to view the contents of the file, no file or directory found error is presented.

No comments:

Post a Comment

Please feel free to leave a comment