首页 > 解决方案 > 遍历所有目录/子目录,获取文件和文件夹的权限

问题描述

下面是遍历所有目录/子目录并获取文件和文件夹的权限的代码片段要求是 fecth 文件、文件夹并检查其他人是否具有 w 权限。我已经设法编写了部分代码,但我遇到了一个错误,我没有看到任何未初始化的值。

以下是错误:

Use of uninitialized value $retMode in bitwise and (&) at myTest.pl line 24.

代码片段:

        use warnings;
        use strict;
        use Data::Dumper;
        use File::stat;
        
        my @dirs = ("/home/mytest");
        my %seen;
        while (my $pwd = shift @dirs) {
                opendir(DIR,"$pwd") or die "Cannot open $pwd\n";
                my @files = readdir(DIR);
                closedir(DIR);
                foreach my $file (@files) {
                        next if $file =~ /^\.\.?$/;
                        my $path = "$pwd/$file";
                        if (-d $path) {
                                next if $seen{$path};
                                $seen{$path} = 1;
                                print "$path \n";
                                push @dirs, $path;
                        }
                        my $info    = stat($path);
                        my $retMode = $info->mode if (defined $info);
                        $retMode = $retMode & 0777;
                        print "$path : $retMode \n";
                        if ($retMode & 002) {
                            # Code comes here if World has write permission on the file
                        }     
                        if ($retMode & 020) {
                            # Code comes here if Group has write permission on the file
                        }

                        #print Dumper \@dirs;
                        # Check for the directory permissions after files
                }
        }

~

输出:

        /home/mytest/.vimBU
        /home/mytest/.vimBU : 488
        /home/mytest/.git
        /home/mytest/.git : 488
        /home/mytest/.profile : 416
        Use of uninitialized value $retMode in bitwise and (&) at myTest.pl line 24.
        /home/mytest/.vim : 0
        /home/mytest/.sh_history : 384
        /home/mytest/.bash_history : 384

这是正确的方法,我试图在文件权限之后获得文件夹权限

标签: perldirectory

解决方案


某些目录您没有权限或与运行时进程相关。它在 readdir(); 之后发生了变化 在第 24 行之前再添加一行,您将看到。

print "No Permission $path\n" and next if not defined $retMode ;

推荐阅读