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)?
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
The module File::Copy::Recursive takes care of that. By default it will copy symlinks and try to preserve ownership.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With