I can see some of you have arrived to my Unix file types post looking for an example of using symlinks in Unix. Today I would like to give you a quick introduction into Unix symlinks.
Symlink is a short name for
symbolic link (sometimes also referred as
soft link) is a special type of file in Unix, which references another file or directory. Symlink contains the name for another file and contains no actual data. To most commands, symlinks look like a regular file, but all the operations (like reading from a file) are referred to the file the symlink points to.
Just to give you an example, here’s how a typical symlink can be created and verified.
First, we create a new text file called
Now, we create a symlink called
/tmp/file.2, which points to the original file of ours. We use the standard Unix ln command, first specifying the target file (the real file we want our symlink to point to), then specify the name of our symbolic link:
If we look at both files, here’s what we see:
If you notice, the /tmp/file.2 has an “l” in the long-format output of the ls command, which confirms it’s a symbolic link. You also can see right away where this symlink points to.
Just to confirm the typical behaviour of a symlink, here’s what happens when we try to show the contents of the /tmp/file.2: we see the contents of the file it points to, /tmp/file.1:
Guess what happens when you remove a symlink? Actually, not much. You only remove the symlink file itself, not the data file it refers to. Here’s what I mean:
While we’re at it, I would also like to explain what an orphan symlink is: it’s a symbolic link which points nowhere, because the original target file it used to point to doesn’t exist anymore.
Here is how an orphan symlink looks. First off, we recreate the symlink and verify it points to /tmp/file.1 once again:
Now, we simply rename the /tmp/file.1 file to /tmp/file.3:
This, naturally, makes /tmp/file.2 an orphan symlink which points to the old /tmp/file.1, but there isn’t a file like this anymore. Attempt to show the contents of /tmp/file.2 will thus fail: