Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move a relative symbolic link?

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?

like image 343
anasdox Avatar asked Dec 15 '11 16:12

anasdox


People also ask

What happens when you move a symlink?

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.

Can symbolic links be relative?

Symbolic link can be of two types Relative or Absolute.

How do I rm a symbolic link?

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.


2 Answers

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.

like image 120
Christopher Neylan Avatar answered Sep 23 '22 17:09

Christopher Neylan


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; } 
like image 20
daxim Avatar answered Sep 20 '22 17:09

daxim