linux - Perl 检查子目录并更改所有权

标签 linux perl subroutine chown

我正在尝试编写一个 perl 脚本,它检查当前目录中的所有目录,然后相应地渗透到后续目录中,直到它包含最后一个目录。这是我写的:

#!/usr/bin/perl -w
use strict;
my @files = <*>;
foreach my $file (@files){
    if (-d $file){
            my $cmd = qx |chown deep:deep $file|;
            my $chdir = qx |cd $file|;
            my @subfiles = <*>:
            foreach my $ subfile(@subfiles){
                if (-d $file){
                    my $cmd = qx |chown deep:deep $subfile|;
                    my $chdir = qx |cd $subfile|;
            .  # So, on in subdirectories
            .
            .
            }
    }

    }
 }

现在,我拥有的一些目录包含大约 50 个子目录。不写50 if条件怎么能穿透呢?请建议。谢谢。

最佳答案

好吧,CS101 方法(如果这只是一个练习)是使用递归函数

sub dir_perms {
 $path = shift;
  opendir(DIR, $path);
  my @files = grep { !/^\.{1,2}$/ } readdir(DIR); # ignore ./. and ./..
  closedir(DIR);
  for (@files) {
   if ( -d $_ ) {
    dir_perms($_);
  }
  else {
   my $cmd = qx |chown deep:deep $_|;
   system($cmd);
  }
 }
}

dir_perms(".");

但我也会查看 File::Find 以获得更优雅和更健壮的东西(这可能会陷入循环链接陷阱,如果您不在目录上调用它,则会出错,等等),并且就此而言,我会查看普通的旧 UNIX find(1),它可以完全按照您尝试使用 -exec 选项执行的操作,例如

/bin/bash$ find /path/to/wherever -type f -exec chown deep:deep {} \;

关于linux - Perl 检查子目录并更改所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20703854/

相关文章:

覆盖几乎所有物理内存的linux memtester

linux - 在 apache access_log 文件中发现错误

multithreading - 从 Perl 线程运行 bash 脚本

perl - 如何找到带有 PPI 的注释,然后在它之前插入代码?

arrays - 试图理解困难的 Perl 语法 : array and empty square braces

abap - 如何将多个参数传递给子程序?

arrays - Qbasic - 尝试调用子系统,但我收到一条消息,显示 "Expected CALL, subname, (...)"

linux - 让 bash 脚本回答交互式提示

linux - 使用来自 shell 变量的 JSON 内容运行 curl 命令

function - 使用接口(interface)将函数作为参数传递给子例程在 Plato Fortran 90 中不起作用