How do I copy symbolic links in Perl?
Asked Answered
Z

3

6

How do I copy a symbolic link (and not the file it points to) in a Perl program while preserving all of the symbolic link attributes (such as owner and permissions)?

Zoie answered 7/1, 2009 at 12:4 Comment(0)
S
9

In Perl you can use the readlink() function to find out the destination of a symlink.

You can also use the lstat() function to read the permissions of the symlink (as opposed to stat() which will read the details of the file pointed to by the symlink).

Actually setting the ownership on the new symlink can't be done without extra help as Perl doesn't expose the lchown() system call. For that you can use the Perl Lchown module from CPAN.

Assuming sufficient permissions (nb: unchecked code)

 use Lchown;
 my $old_link = 'path to the symlink';
 my $new_link = 'path to the copy';

 my $dst = readlink($old_link);
 my @stat = lstat($old_link);

 symlink $dst, $new_link;
 lchown $stat[4], $stat[5], $new_link;  # set UID and GID from the lstat() results

You don't need to worry about the permissions on the symlink - they always appear as -rwxrwxrwx

Sitar answered 7/1, 2009 at 12:13 Comment(2)
Thanks. I didn't notice symlinks has no real permissions. I need to think how badly I need the owner change.Zoie
also note that if the content of the symlink is a relative path then it may need rewriting if the $old_link and $new_link aren't in the same directory!Sitar
T
4

The module File::Copy::Recursive takes care of that. By default it will copy symlinks and try to preserve ownership.

Thankless answered 7/1, 2009 at 12:51 Comment(2)
Thanks for the pointer. I don't have it in my distribution, and I need to consider if I want to add this module. I also see in the source that the owner of the file is not handled. I need to re-think how important it is for me.Zoie
I agree with splintor - whilst this works, the module is not in the default install so it won't be a good solution if you want to avoid your users needing to install dependencies.Sirrah
F
0

Depending on your use case regarding absolute vs. relative target paths, dir hierarchy etc., using link to create a hardlink to the symlink you want to copy might be enough already as well. No extra packages needed and creating hardlinks is supported by Perl on many platforms as well.

Forerun answered 7/12, 2018 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.