mv a file without breaking a symlink to that file
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
Related videos on Youtube
gabe.
Software Development Manager, developer, command line adept.
Updated on September 18, 2022Comments
-
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:- get the target of the link
- mv the target
- recreate the link to the new target
- 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:
- 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 over 12 yearsHard links don't have this problem. They have other drawbacks though. :-)
-
Admin over 12 yearsYeah, can't use hardlinks as the files are across several file systems.
-
Admin about 6 yearsAlso: can't hardlink to a directory.
-
gabe. over 12 yearsHeh, 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 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 requiresln -s -f
.. (I've made the adjustment) -
Peter.O over 12 yearsNote: it will be more complicated if a chain of links is involved.