How to batch-export all the content contained in symbolic links? (and then delete them all)

lnsymlink

So as an alternative to Recursive scp without following links or creating a giant tar file? (this could be an emergency since the remote files could be deleted any time soon), I'm thinking of deleting all my symbolic links. But then I would like to batch-export them all somewhere so that I can restore them once I'm done with the scp file copying.

Best Answer

You could make a tar archive containing the symbolic links only. Assuming GNU utilities (so non-embedded Linux or Cygwin):

cd /some/dir
tar cf symlinks.tar --no-recursion .
find -type l -print0 | xargs -0 tar rf symlinks.tar

Another approach is to generate a shell script that would recreate the symlinks. Here's a Perl approach (while this is doable with only POSIX utilities, it's difficult to handle special characters correctly).

use File::Find;
sub wanted {
    if (-L $_) {
        $link_name = $_;
        $target = readlink($_);
        die $! if !defined $target;
        # protect single quotes from shell expansion
        $link_name =~ s/\x27/\x27\\\x27\x27/;
        $target =~ s/\x27/\x27\\\x27\x27/;
        print "ln -s -- \x27$target\x27 \x27$link_name\x27\n";
    }
}
find({wanted => \&wanted, no_chdir => 1}, ".")

Don't remove the symbolic links. Exclude them from the copy, or make a symlink-less copy of the directory tree, as illustrated in my answer to your other question.

Related Question