How do I move a relative symbolic link?

2020-05-29 19:56发布

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?

4条回答
迷人小祖宗
2楼-- · 2020-05-29 20:23

One can use tar to move a folder containing relative symbolic links.

For example:

cd folder_to_move/..
tar czvf files.tgz folder_to_move
cd dest_folder/..
tar xzvf /absolute/path/to/folder_to_move/../files.tgz

# If all is fine, clean-up
rm /absolute/path/to/folder_to_move/../files.tgz
rm -rf /absolute/path/to/folder_to_move
查看更多
劳资没心,怎么记你
3楼-- · 2020-05-29 20:26

Improving on Christopher Neylan's answer:

~/bin $ cat mv_ln
#!/bin/bash
#
# inspired by https://stackoverflow.com/questions/8523159/how-do-i-move-a-relative-symbolic-link#8523293
#          by Christopher Neylan

help() {
   echo 'usage: mv_ln src_ln dest_dir'
   echo '       mv_ln --help'
   echo
   echo '  Move the symbolic link src_ln into dest_dir while'
   echo '  keeping it relative'
   exit 1
}

[ "$1" == "--help" ] || [ ! -L "$1" ] || [ ! -d "$2" ] && help

set -e # exit on error

orig_link="$1"
orig_name=$( basename    "$orig_link" )
orig_dest=$( readlink -f "$orig_link" )
dest_dir="$2"

ln -r -s "$orig_dest" "$dest_dir/$orig_name"
rm "$orig_link"

This is also part of https://github.com/tpo/little_shell_scripts

查看更多
女痞
4楼-- · 2020-05-29 20:30

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;
}
查看更多
可以哭但决不认输i
5楼-- · 2020-05-29 20:43

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.

查看更多
登录 后发表回答