views:

1369

answers:

2

Hi all,

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)?

Thanks, splintor

+6  A: 

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

Alnitak
Thanks. I didn't notice symlinks has no real permissions. I need to think how badly I need the owner change.
splintor
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!
Alnitak
+3  A: 

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

innaM
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.
splintor