Skip to content
Advertisement

Shell Mount and check directionairy existence

Just looking for some help with my mounting shell script, wondering if anyone could advice me on how to make it check for the directory at the mount point exists and is empty, or is created by the script if it does not exist

#!/bin/bash

MOUNTPOINT="/myfilesystem"

if grep -qs "$MOUNTPOINT" /proc/mounts; then
    echo "It's mounted."
else
    echo "It's not mounted."

    mount "$MOUNTPOINT"

    if [ $? -eq 0 ]; then
        echo "Mount success!"
    else
        echo "Something went wrong with the mount..."
    fi
fi

Advertisement

Answer

Your use of grep will return any mountpoint that contains the string /myfilesystem in… e.g: both of these:

  • /myfilesystem
  • /home/james/myfilesystem

Prefer to use something more prescriptive like the following:

mountpoint -q "${MOUNTPOINT}"

You can use [ to test if a path is a directory:

if [ ! -d "${MOUNTPOINT}" ]; then
    if [ -e "${MOUNTPOINT}" ]; then
        echo "Mountpoint exists, but isn't a directory..."
    else
        echo "Mountpoint doesn't exist..."
    fi
fi

mkdir -p will create all parent directories, as necessary:

mkdir -p "${MOUNTPOINT}"

Finally, test if a directory is empty by exploiting bash’s variable expansion:

[ "$(echo ${MOUNTPOINT}/*)" != "${MOUNTPOINT}/*" ]

It’s also a good idea to run scripts with some level of ‘safety’. See the set built-in command: https://linux.die.net/man/1/bash

-e      Exit immediately if a pipeline (which may consist of a single simple command), a
        list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero
        status.
-u      Treat unset variables and parameters other than the special parameters "@" and "*"
        as an error when performing parameter expansion.

In full: (note bash -eu)

#!/bin/bash -eu

MOUNTPOINT="/myfilesystem"

if [ ! -d "${MOUNTPOINT}" ]; then
    if [ -e "${MOUNTPOINT}" ]; then
        echo "Mountpoint exists, but isn't a directory..."
        exit 1
    fi
    mkdir -p "${MOUNTPOINT}"
fi

if [ "$(echo ${MOUNTPOINT}/*)" != "${MOUNTPOINT}/*" ]; then
    echo "Mountpoint is not empty!"
    exit 1
fi

if mountpoint -q "${MOUNTPOINT}"; then
    echo "Already mounted..."
    exit 0
fi

mount "${MOUNTPOINT}"
RET=$?
if [ ${RET} -ne 0 ]; then
    echo "Mount failed... ${RET}"
    exit 1
fi

echo "Mounted successfully!"
exit 0
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement