How to check if a filesystem is mounted with a script
Many Linux distros have the mountpoint
command. It can explicitly used to check if a directory is a mountpoint. Simple as this:
#!/bin/bash
if mountpoint -q "$1"; then
echo "$1 is a mountpoint"
else
echo "$1 is not a mountpoint"
fi
You can check the status code of mount
, and most well written executables, with the shell special parameter ?
.
From man bash
:
? Expands to the exit status of the most recently executed foreground pipeline.
After you run the mount
command, immediately executing echo $?
will print the status code from the previous command.
# mount /dev/dvd1 /mnt
mount: no medium found on /dev/sr0
# echo $?
32
Not all executables have well defined status codes. At a minimum, it should exit with a success (0) or failure (1) code, but that's not always the case.
To expand on (and correct) your example script, I added a nested if
construct for clarity. It's not the only way to test the status code and perform an action, but it's the easiest to read when learning.
#!/bin/bash
mount="/myfilesystem"
if grep -qs "$mount" /proc/mounts; then
echo "It's mounted."
else
echo "It's not mounted."
mount "$mount"
if [ $? -eq 0 ]; then
echo "Mount success!"
else
echo "Something went wrong with the mount..."
fi
fi
For more information on "Exit and Exit Status", you can refer to the Advanced Bash-Scripting Guide.
One more way:
if findmnt ${mount_point}) >/dev/null 2>&1 ; then
#Do something for positive result (exit 0)
else
#Do something for negative result (exit 1)
fi