Detecting a Mount in BASH

Written by Mark Sanborn: Jun 30, 2008

Often times we will use bash to create scripts for backing up or transfering files. A lot of times these files are transfered over a mounted network share or an external usb drive. Since these mount points are not always mounted we need to come up with a script that will detect the mount before we perform our operation. I have come up with a script that I think is simple enough that uses df and grep to detect the mount.

The code

if df | grep -q '/mnt/yourMountPoint'
        echo "Found mount point, running task"
        # Do something
        echo "Error, disk is not mounted"
        exit -1


The df command will print out the current disk usage information on all the mount points. We then pipe ‘|’ the information to grep. Grep searches through for the string. In our case we are using, ‘/mnt/yourMountPoint’. The ‘-q’ switch we are passing through tells grep to return an exit signal instead of printing the matching text to the screen. This allows us to write our if statement without filling up a log file full of ‘/mnt/yourMountPoint’ strings.

Once you have your script running you might want to have it run automatically with cron.

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.