< Previous | Contents | Next >
Creating Symbolic Links
Symbolic links were created to overcome the two disadvantages of hard links: Hard links cannot span physical devices and hard links cannot reference directories, only files. Sym- bolic links are a special type of file that contains a text pointer to the target file or direc- tory.
Creating symbolic links is similar to creating hard links:
[me@linuxbox playground]$ ln -s fun fun-sym [me@linuxbox playground]$ ln -s ../fun dir1/fun-sym [me@linuxbox playground]$ ln -s ../fun dir2/fun-sym
[me@linuxbox playground]$ ln -s fun fun-sym [me@linuxbox playground]$ ln -s ../fun dir1/fun-sym [me@linuxbox playground]$ ln -s ../fun dir2/fun-sym
The first example is pretty straightforward, we simply add the “-s” option to create a symbolic link rather than a hard link. But what about the next two? Remember, when we create a symbolic link, we are creating a text description of where the target file is rela - tive to the symbolic link. It's easier to see if we look at the ls output:
[me@linuxbox playground]$ ls -l dir1
[me@linuxbox playground]$ ls -l dir1
total 4 | ||
-rw-r--r-- 4 me | me | 1650 2016-01-10 16:33 fun-hard |
lrwxrwxrwx 1 me | me | 6 2016-01-15 15:17 fun-sym -> ../fun |
The listing for fun-sym in dir1 shows that it is a symbolic link by the leading “l” in the first field and that it points to “../fun”, which is correct. Relative to the location of fun-sym, fun is in the directory above it. Notice too, that the length of the symbolic link file is 6, the number of characters in the string “../fun” rather than the length of the file to which it is pointing.
When creating symbolic links, you can either use absolute pathnames:
[me@linuxbox playground]$ ln -s /home/me/playground/fun dir1/fun-sym
[me@linuxbox playground]$ ln -s /home/me/playground/fun dir1/fun-sym
or relative pathnames, as we did in our earlier example. In most cases, using relative pathnames is more desirable because it allows a directory tree containing symbolic links and their referenced files to be renamed and/or moved without breaking the links.
In addition to regular files, symbolic links can also reference directories:
[me@linuxbox playground]$ ln -s dir1 dir1-sym
[me@linuxbox playground]$ ls -l
total 16
drwxrwxr-x | 2 | me | me | 4096 | 2016-01-15 | 15:17 | dir1 |
lrwxrwxrwx | 1 | me | me | 4 | 2016-01-16 | 14:45 | dir1-sym -> dir1 |
drwxrwxr-x | 2 | me | me | 4096 | 2016-01-15 | 15:17 | dir2 |
-rw-r--r-- | 4 | me | me | 1650 | 2016-01-10 | 16:33 | fun |
-rw-r--r-- | 4 | me | me | 1650 | 2016-01-10 | 16:33 | fun-hard |
lrwxrwxrwx | 1 | me | me | 3 | 2016-01-15 | 15:15 | fun-sym -> fun |