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.

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

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.

|improve this answer|||||
  • 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. Aug 23 '11 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. Aug 23 '11 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 Aug 23 '11 at 17:12

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)"
  mv "$org" "$new"
  ln -s -f "$new" "$new".link  # '-s' for a soft link
|improve this answer|||||
  • Note: it will be more complicated if a chain of links is involved. – Peter.O Aug 23 '11 at 18:09

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.