如何在 Perl 中复制符号链接?

发布于 2024-07-10 14:20:53 字数 60 浏览 5 评论 0原文

如何在 Perl 程序中复制符号链接(而不是它指向的文件),同时保留所有符号链接属性(例如所有者和权限)?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我们只是彼此的过ke 2024-07-17 14:20:53

在 Perl 中,您可以使用 readlink() 函数来查找符号链接的目标。

您还可以使用 lstat() 函数读取符号链接的权限(与 stat() 不同,后者将读取符号链接指向的文件的详细信息)。

实际上,如果没有额外的帮助,就无法在新符号链接上设置所有权,因为 Perl 不会公开 lchown() 系统调用。 为此,您可以使用 CPAN 中的 Perl Lchown 模块。

假设有足够的权限(注意:未经检查的代码)

 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

您无需担心符号链接的权限 - 它们始终显示为 -rwxrwxrwx

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

青衫儰鉨ミ守葔 2024-07-17 14:20:53

模块 File::Copy::Recursive 负责处理的。 默认情况下,它将复制符号链接并尝试保留所有权。

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

残月升风 2024-07-17 14:20:53

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文