Search code examples
linuxgnu-coreutilsln

Why ln -sf does not overwrite existing link to directory


According to documentation, command ln -f removes existing destination file. Does this mean that if I create a symlink, -f should remove of overwrite any existing symlink at destination?

I have a symlink, say, L, pointing to DIR1 and type ln -sf DIR2 L. But L still points to DIR1. Only after rm L this command creates a link pointing to DIR2.

With symlinks to files it behaves as expected.

What's wrong with links to directories? (bash 4.3.48 on Ubuntu 16.04.2 LTS and Windows WSL)


Solution

  • When you run:

    ln -sf DIR2 L
    

    This is creating a symlink inside DIR1, because symlink L points to directory DIR1 and ln dereferences the symlink L, resulting in creation of L/DIR2 -> DIR1.

    The following:

    #rm -fr DIR1 DIR2 L
    mkdir DIR1 DIR2
    ln -v -s DIR1 L
    ls -la L
    ln -v -f -s DIR2 L
    ls -la L
    

    will output:

    'L' -> 'DIR1'
    lrwxrwxrwx 1 runner runner 4 Oct 21 18:13 L -> DIR1
    'L/DIR2' -> 'DIR2'
    lrwxrwxrwx 1 runner runner 4 Oct 21 18:13 L -> DIR1
    

    To handle that, use the --no-dereference option as indicated in answer in this thread on superuser.com.