如何使用 Perl 递归设置只读权限?

发布于 2024-09-19 18:00:47 字数 60 浏览 1 评论 0原文

我希望 $dir 及其下面的所有内容都是只读的。我如何使用 Perl 进行设置?

I would like $dir and everything underneath it to be read only. How can I set this using Perl?

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

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

发布评论

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

评论(3

您的好友蓝忘机已上羡 2024-09-26 18:00:47

您可以使用 File::Find 和 chmod 的组合来执行此操作(请参阅 < a href="http://perldoc.perl.org/functions/chmod.html" rel="nofollow noreferrer">perldoc -f chmod):

use File::Find;

sub wanted
{
    my $perm = -d $File::Find::name ? 0555 : 0444;
    chmod $perm, $File::Find::name;
}
find(\&wanted, $dir);

You could do this with a combination of File::Find and chmod (see perldoc -f chmod):

use File::Find;

sub wanted
{
    my $perm = -d $File::Find::name ? 0555 : 0444;
    chmod $perm, $File::Find::name;
}
find(\&wanted, $dir);
指尖凝香 2024-09-26 18:00:47
system("chmod", "--recursive", "a-w", $dir) == 0
  or warn "$0: chmod exited " . ($? >> 8);
system("chmod", "--recursive", "a-w", $dir) == 0
  or warn "$0: chmod exited " . ($? >> 8);
多像笑话 2024-09-26 18:00:47

未经测试但应该可以。请注意,您的目录本身必须保持可执行状态。

set_perms($dir);

sub set_perms {
     my $dir = shift;
     opendir(my $dh, $dir) or die $!;
     while( (my $entry = readdir($dh) ) != undef ) {
          next if $entry =~ /^\.\.?$/;
          if( -d "$dir/$entry" ) {
              set_perms("$dir/$entry");
              chmod(0555, "$dir/$entry");
          }
          else {

              chmod(0444, "$dir/$entry");
          }
     }
     closedir($dh);
}

当然,您也可以从 Perl 执行 shell 命令:

system("find $dir -type f | xargs chmod 444");
system("find $dir -type d | xargs chmod 555");

如果您有很多条目,我会使用 xargs。

Untested but it should work. Note your directories themselves have to stay executable

set_perms($dir);

sub set_perms {
     my $dir = shift;
     opendir(my $dh, $dir) or die $!;
     while( (my $entry = readdir($dh) ) != undef ) {
          next if $entry =~ /^\.\.?$/;
          if( -d "$dir/$entry" ) {
              set_perms("$dir/$entry");
              chmod(0555, "$dir/$entry");
          }
          else {

              chmod(0444, "$dir/$entry");
          }
     }
     closedir($dh);
}

Of course you could execute a shell command from Perl as well:

system("find $dir -type f | xargs chmod 444");
system("find $dir -type d | xargs chmod 555");

I use xargs in case you have a lot of entries.

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