29

Is there a way to replace the value of a symbolic link?

For example, I want to change a symbolic link from this:

first -> /home/username/foo/very/long/directories/that/I/do/not/want/to/type/again

to this:

second -> /home/username/bar/very/long/directories/that/I/do/not/want/to/type/again

I want to change only foo to bar.

Of course I can create a link again, but if it is possible to replace the value of the link, it becomes easier.

1
  • This is not a duplicate, IMO. The other one just talks about repointing a symlink. This question is talking about modifying just a part of the symlink. That responses makes no mention of readlink.
    – MrMas
    Jan 26 at 23:24

2 Answers 2

36

You can use the -f, --force option of ln to have it remove the existing symlink before creating the new one. If the destination is a directory, you need to add the -n, --no-dereference option to tell ln to treat the symlink as a normal file.

ln -sfn target existing_link

However, this operation is not atomic, as ln will unlink() the old symlink before calling symlink(), so technically it doesn't count as changing the value of the link. If you care about this distinction, then the answer is no, you can't change the value of an existing symlink.

That said, you can do something like the following to create a new symlink, changing part of the old link value:

  ln -sfn "$(readlink existing_link | sed s/foo/bar/)" "existing_symlink"
1
1
second -> /home/username/bar/very/long/directories/that/I/do/not/want/to/type/again

If you are running inside X:

stat second

Will print the link and some other information. Type ln -s, then highlight /home/username/bar/very/long/directories/that/I/do/not/want/to/type/again with the mouse cursor. Press the middle button (or both buttons if you only have two). The long line you didn't want to type again will be pasted at the text cursor.

If you aren't in X, you can do the same thing by installing gpm.

Not the answer you're looking for? Browse other questions tagged .