11

I have a particular directory full of other directories organized (named) by date. For ease of reference, I have a symlink called current pointing to the latest one.

In the script that creates new date directories, I wish to create or fix the current symlink to point to the newest directory once created.

I thought the appropriate command would just be, e.g.,

ln -fs 2017-03-01 current

If the current symlink doesn't exist yet, this works.


However, if the current symlink has already been created (and points, let us say, at the directory 2017-02-28), this doesn't work:

Instead of removing the symlink current and creating a new symlink current which points to 2017-03-01, the result will instead be a broken symlink called 2017-03-01 pointing to itself, resting inside the directory 2017-02-28 (which is where the symlink current pointed and still points).

This baffled me, so I read the specs for ln. Turns out this is expected behavior:

SYNOPSIS

ln [-fs] [-L|-P] source_file target_file

ln [-fs] [-L|-P] source_file... target_dir

DESCRIPTION

...

The second synopsis form shall be assumed when the final operand names an existing directory.


It seems, then, that there is no way whatsoever to repoint a symlink that currently points to a directory to a new target, where the new target has a name different from the name of the symlink. So ln -fs doesn't work the way I thought it did.

Must I rm current, or is there another approach I've overlooked?

17

In GNU's ln, there is ln -n, which would allow re-pointing a symlink:

$ mkdir dir1 dir2
$ ln -s dir1 sym
# dir1/
# dir2/
# sym -> dir1/

$ ln -nsf dir2 sym
# dir1/
# dir2/
# sym -> dir2/

BSD coreutils uses the flag -h the same way -n would be used, but it is likely the binary may support -n just for compatibility with GNU.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.