Search code examples
perlunixsystem

Check if a directory exists as an absolute path


How would one check if the path/directory exists (-d) and is a full pathname from root directory?

i.e. ~/mysubdir vs /home/me/mysubdir vs mysubdir. 
  • I want the argument supplied to die if it is not a root path that exists. os specific for unix.
  • Or, given a directory, get its full root path if it exists?

Solution

  • use strict;
    use warnings;
    use feature 'say';
    
    use Cwd qw/abs_path getcwd/;
    use File::HomeDir;
    
    my $path = 'foo/../bar';
    
    if($path =~ /^~/) {
        my $home = File::HomeDir->my_home;
        $path =~ s/^~/$home/;
    }
    
    if($path !~ m!^/!) {
        $path = getcwd . "/$path";
    }
    
    my $full_path = abs_path($path);
    
    if(defined $full_path && -d $full_path) {
        say "$full_path exists";
    } else {
        say "$path is non-existant";
    }
    

    File::Homedir will allow you to get a users home directory, and you can then replace the tilde in the path.

    If the path at this point doesn't start with / (is a relative path) prepend the current working directory with getcwd, to get an absolute path.

    Once you've done that you can pass it through abs_path to resolve things like . and .. as well as symlinks.

    Finally you can then test that with -d to see if the resultant path exists.