Perl: Get file permissions

If you need to see if a file is world readable you'll need to be able to break out file permissions.

my @p     = get_file_permissions("/tmp/foo.txt");
my $other = $p[2];

# 4 = readable, 2 = writeable, 1 = executable
if ($other & 4) { print "File is world readable\n"; }
if ($other & 2) { print "File is world writeable\n"; }
if ($other & 1) { print "File is world executable\n"; }
sub get_file_permissions {
    my $file = shift();

    my @x    = stat($file);
    my $mode = $x[2];

    my $user  = ($mode & 0700) >> 6;
    my $group = ($mode & 0070) >> 3;
    my $other = ($mode & 0007);

    my @ret = ($user, $group, $other);

    return @ret;
}

If you want a dedicated function it's pretty simple:

sub is_world_readable {
    my $file  = shift();
    if (!-r $file) { return undef; }

    my @x     = stat($file);
    my $perms = $x[2];

    my $ret = $perms & 0006; # Readable

    return $ret;
}
Leave A Reply
All content licensed under the Creative Commons License