How to use Perl to check mount point?

This is a Perl module that was posted in a comment by our friend Justy (a.k.a. the iSheep), it solves a problem that I’ve faced a lot, especially with Perl scripts that run as daemons, where you need to copy files to a mount point. but if the mount point has failed then you’re just copying the files to the local directory that once represented the mount! So here’s the code to make sure there’s a ‘point’ in your mount.

Usage:

CheckMount::isMounted({ mount => $srcMount });

The module:

package CheckMount;

#
# Checks the Proc Filesystem for a mounted mount point
# Returns 1 if the mount point is mounted else 0
#

sub isMounted{
my $checkThisMount = shift;
my $procMountFile = “/proc/mounts”;
my @mountAry = ();

open(FILE, $procMountFile) or die(“SORRY, UNSUPPORTED”);

while (<FILE>) {
chomp();
my @tmp = split(/s+/, $_);
push(@mountAry, @tmp[1]);
} close(FILE);

foreach my $mount(@mountAry) {
my $tmp = $mount;
if ($tmp =~ /^$checkThisMount$/) { print “YESn”; }
}
return 0;
}

1;

Then, you can use isMounted(“/data”); to check your mount point. There’s also another way like this

grep m{/}, qx{/bin/mount} and print “/ mountedn”;

This may have an issue, if “/home” is another mount
point, “grep m{/}, qx{/bin/mount}” will be true again, so the mount
point you are going to check should be in the most depth of mount path.

Share Button

2 thoughts on “How to use Perl to check mount point?

  1. #Fixed version https://gist.github.com/partizanes/bde5b82f1cf3fef0875b0b11f13f485f
    #
    # Checks the Proc Filesystem for a mounted mount point
    # Returns 1 if the mount point is mounted else 0
    #

    sub isMounted {
    my $checkThisMount = shift;
    my $procMountFile = “/proc/mounts”;
    my@ mountAry = ();

    open my $handle, ‘<', $procMountFile;
    chomp(my@ lines = );
    close $handle;

    foreach(@lines) {
    if ($_ = ~m / $checkThisMount / ) {
    return 1;
    }
    }

    return 0;
    }

    print(isMounted(“/dump1”));

Leave a comment

Your email address will not be published. Required fields are marked *