Check if directory mounted with bash Check if directory mounted with bash linux linux

Check if directory mounted with bash


You didn't bother to mention an O/S.

Ubuntu Linux 11.10 (and probably most up-to-date flavors of Linux) have the mountpoint command.

Here's an example on one of my servers:

$ mountpoint /oracle/oracle is a mountpoint$ mountpoint /bin/bin is not a mountpoint

Actually, in your case, you should be able to use the -q option, like this:

mountpoint -q /foo/bar || mount -o bind /some/directory/here /foo/bar

Hope that helps.


Running the mount command without arguments will tell you the current mounts. From a shell script, you can check for the mount point with grep and an if-statement:

if mount | grep /mnt/md0 > /dev/null; then    echo "yay"else    echo "nay"fi

In my example, the if-statement is checking the exit code of grep, which indicates if there was a match. Since I don't want the output to be displayed when there is a match, I'm redirecting it to /dev/null.


The manual of mountpoint says that it:

checks whether the given directory or file is mentioned in the /proc/self/mountinfo file.

The manual of mount says that:

The listing mode is maintained for backward compatibility only. For more robust and customizable output use findmnt(8), especially in your scripts.

So the correct command to use is findmnt, which is itself part of the util-linux package and, according to the manual:

is able to search in /etc/fstab, /etc/mtab or /proc/self/mountinfo

So it actually searches more things than mountpoint. It also provides the convenient option:

-M, --mountpoint path

Explicitly define the mountpoint file or directory. See also --target.

In summary, to check whether a directory is mounted with bash, you can use:

if [[ $(findmnt -M "$FOLDER") ]]; then    echo "Mounted"else    echo "Not mounted"fi

Example:

mkdir -p /tmp/foo/{a,b}cd /tmp/foosudo mount -o bind a btouch a/filels b/ # should show filerm -f b/filels a/ # should show nothing[[ $(findmnt -M b) ]] && echo "Mounted"sudo umount b[[ $(findmnt -M b) ]] || echo "Unmounted"