mv a file without breaking a symlink to that file

24,612

Solution 1

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.

Solution 2

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
Share:
24,612

Related videos on Youtube

gabe.
Author by

gabe.

Software Development Manager, developer, command line adept.

Updated on September 18, 2022

Comments

  • gabe.
    gabe. over 1 year

    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.

    • Admin
      Admin over 12 years
      Hard links don't have this problem. They have other drawbacks though. :-)
    • Admin
      Admin over 12 years
      Yeah, can't use hardlinks as the files are across several file systems.
    • Admin
      Admin about 6 years
      Also: can't hardlink to a directory.
  • gabe.
    gabe. over 12 years
    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.
  • Peter.O
    Peter.O over 12 years
    @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
    Peter.O over 12 years
    Note: it will be more complicated if a chain of links is involved.