Search code examples
perlfilestat

Determine user/group ownership for a directory


I have a perl script that will perform some operations on directories, and I only wait it to run on directories for which the current user(e.g. the user executing the script) has ownership.

I've tried the following:

...
my $user = getlogin();
opendir(HANDLE, $path) or die ("No such directory: $path");
foreach my $directory (readdir HANDLE)
{
    opendir(WORKING_DIR_HANDLE, "$path/$directory") or die ("!!!!!!!");
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat(WORKING_DIR_HANDLE);
    my $owner = getpwuid($uid);
    if( $owner eq $user )
    {
      ...
    }
}
...

The code works for the most part. However, the call to stat() returns undefined values. According to the perl docs, I think I am making the stat() call correctly:

* stat FILEHANDLE
* stat EXPR
* stat DIRHANDLE
* stat

 Returns a 13-element list giving the status info for a file, either the file opened via
 FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats $_ . Returns the 
 empty list if stat fails. Typically used as follows:

I have also tried just pasing it an EXPR using the file name, and I get the same results. Am I just missing something obvious? Or is there another way to do this? I would prefer a solution that does not require installing third-party perl modules.


Solution

  • stat returns an empty list on failure, which sets all those variables to undef. Add or die $! after the call to find out why it failed:

    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
       = stat(WORKING_DIR_HANDLE) or die $!;
    

    Once you know why it failed, you may be able to figure out how to fix it. If not, then add the error message to your question.