I have a lot of relative symbolic links that I want to move to another directory.
How can I move symbolic links (those with a relative path) while preserving the right path?
Answer. What happens to symlink if we rename a file ? Once you move a file to which symlink points, symlink is broken aka dangling symlink. You have to delete it and create new one if you want to point to the new filename.
Symbolic link can be of two types Relative or Absolute.
To remove a symbolic link, use either the rm or unlink command followed by the name of the symlink as an argument. When removing a symbolic link that points to a directory do not append a trailing slash to the symlink name.
You can turn relative paths into full paths using readlink -f foo
. So you would do something like:
ln -s $(readlink -f $origlink) $newlink rm $origlink
EDIT:
I noticed that you wish to keep the paths relative. In this case, after you move the link, you can use symlinks -c
to convert the absolute paths back into relative paths.
This is a perl
solution that preserves relative paths:
use strictures; use File::Copy qw(mv); use Getopt::Long qw(GetOptions); use Path::Class qw(file); use autodie qw(:all GetOptions mv); my $target; GetOptions('target-directory=s' => \$target); die "$0 -t target_dir symlink1 symlink2 symlink3\n" unless $target && -d $target; for (@ARGV) { unless (-l $_) { warn "$_ is not a symlink\n"; next; } my $newlink = file(readlink $_)->relative($target)->stringify; unlink $_; symlink $newlink, $_; mv $_, $target; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With