Hypercipient

The ln Command - All About Links

With most of my work happening in containers, I don’t have a massive need to use links. They do come up occassionally, and I wanted to to a bit of studying to give myself a solid understanding of them. These are some notes I collected. These were performed on Ubuntu 24.10, and I cannot say for sure results on different distributions will behave in subtly different ways.

Let’s start with a basic example. Start with a directory.

mkdir dir-1.0

Maybe we want to be able to refer this directory using a stable name, and we also want to be able to drop a new directory, version 2.0, with updated contents. We can create a ‘soft’ link to the directory.

ln -s dir-1.0 current

Here we specify the target directory followed by the name of the link we want to create. Listing the results gives us the following.

ls -lt
lrwxrwxrwx 1 user0 user0   7 May  1 11:28 current -> dir-1.0
drwxrwxr-x 2 user0 user0   2 May  1 11:28 dir-1.0

If we want to update current to point to a new directory, the link can be updated in a single command. First, create a new directory. Add a couple of files so we can ensure we can really distinguish the old directory from the new one.

mkdir dir-1.1
touch dir-1.1/file1
touch dir-1.1/file2

Now we can update the link using the switches -f and -n.

ln -s -n -f dir-1.1 current

Here is what you should see when doing an ls -l

lrwxrwxrwx 1 user0 user0   7 May  1 11:52 current -> dir-1.1
drwxrwxr-x 2 user0 user0   3 May  1 11:47 dir-1.0
drwxrwxr-x 2 user0 user0   4 May  1 11:51 dir-1.1

The updated link can be confirmed by running ls current, which will show something like the following.

ls current
file1   file2

Note: If you try ls -l current, you might just see the long listing of the link pointing to its target, that is, current -> dir-1.1. So see a long list of the contents of current, run ls -l current/ (with a trailing slash, thus treating it as a directory rather than a link. If you want a long listing but do not want the trailing slash added, run ls -l --dereference or ls -lL, which will dereference the link.

Tags: