27

Is it possible to mv a file w/out breaking a symbolic link to that file? My initial response to this is no, and I'm working out a script based solution to change the links immediately following the move, but I was wondering how others have approached this issue. The paths and names of the symlinks are known in advance, so In theory all I need to do is:

  1. get the target of the link
  2. mv the target
  3. recreate the link to the new target
  4. create a new link to the new target (different than the original link, which I still want to keep for now)

At a later date:

  1. delete the old link

1-4 will be encapsulated in a bash script, but I'm wondering if anyone has a more elegant approach, or knows of a built-in or command that I'm not aware of.

3
  • 3
    Hard links don't have this problem. They have other drawbacks though. :-) Commented Aug 23, 2011 at 15:30
  • 4
    Yeah, can't use hardlinks as the files are across several file systems.
    – gabe.
    Commented Aug 23, 2011 at 16:09
  • 3
    Also: can't hardlink to a directory.
    – user6860
    Commented Apr 23, 2018 at 18:01

2 Answers 2

8

You are on the right track, I don't think there is an easier way than the sequence you describe.

Steps 3 and 4 are a little confusing. If you want to re-target existing links you keeping the same name you can use ln -f to overwrite existing files. If you want the name of your links to also change to reflect the new target name, your sequence is correct.

3
  • 1
    Heh, yeah, just re-read that part and now I've confused myself as well. I'll tweak it so it makes more sense. Thanks.
    – gabe.
    Commented Aug 23, 2011 at 15:22
  • I'm a bit confused on the use of ln -f, but I think the script @fred posted may help clarify how it works. The man page wasn't much help, surprisingly.
    – gabe.
    Commented Aug 23, 2011 at 16:17
  • @gabe. The original version of my answer had the correct -s -f, but while mofifying it, it "lost" the -s: wrong! From wikipedia: 'ln' with no options creates a hard link, 'ln -f' forces a hard link ... so thanks for the question, it has really confirmed the syntax for me now.. It certainly made me double-check things... It requires ln -s -f.. (I've made the adjustment)
    – Peter.O
    Commented Aug 23, 2011 at 17:12
4

For your situation:

# change target of a symbolic link
# -------------
# ln -s, --symbolic    make symbolic links instead of hard links
# ln -f, --force       remove existing destination files
#
# Setup: make junk.link to  file junk
  echo hello > ~/junk
  ln -s ~/junk ~/junk.link;  cat ~/junk.link
#
# move file and point the link to it.
  org="$(readlink ~/junk.link)"
  new="$org".moved
  mv "$org" "$new"
  ln -s -f "$new" "$new".link  # '-s' for a soft link
1
  • Note: it will be more complicated if a chain of links is involved.
    – Peter.O
    Commented Aug 23, 2011 at 18:09

You must log in to answer this question.

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