What's the best way to check if a volume is mounted in a Bash script?
Solution 1:
Avoid using /etc/mtab
because it may be inconsistent.
Avoid piping mount
because it needn't be that complicated.
Simply:
if grep -qs '/mnt/foo ' /proc/mounts; then
echo "It's mounted."
else
echo "It's not mounted."
fi
(The space after the /mnt/foo
is to avoid matching e.g. /mnt/foo-bar
.)
Solution 2:
if mountpoint -q /mnt/foo
then
echo "mounted"
else
echo "not mounted"
fi
or
mountpoint -q /mnt/foo && echo "mounted" || echo "not mounted"
Solution 3:
findmnt -rno SOURCE,TARGET "$1"
avoids all the problems in the other answers. It cleanly does the job with just one command.
Other approaches have these downsides:
-
grep -q
andgrep -s
are an extra unnecessary step and aren't supported everywhere. -
/proc/\*
isn't supported everywhere. (mountpoint
is also based on proc). -
mountinfo
is based on /proc/.. -
cut -f3 -d' '
messes up spaces in path names - Parsing mount's white space is problematic. It's man page now says:
.. listing mode is maintained for backward compatibility only.
For more robust and customizable output use findmnt(8), especially in your scripts.
Bash functions:
#These functions return exit codes: 0 = found, 1 = not found
isDevMounted () { findmnt --source "$1" >/dev/null;} #device only
isPathMounted() { findmnt --target "$1" >/dev/null;} #path only
isMounted () { findmnt "$1" >/dev/null;} #device or path
#Usage examples:
if isDevMounted "/dev/sda10";
then echo "device is mounted"
else echo "device is not mounted"
fi
if isPathMounted "/mnt/C";
then echo "path is mounted"
else echo "path is not mounted"
fi
#Universal (device OR path):
if isMounted "/dev/sda10";
then echo "device is mounted"
else echo "device is not mounted"
fi
if isMounted "/mnt/C";
then echo "path is mounted"
else echo "path is not mounted"
fi