sh scripting: how to mount a remote filesystem if it is not mounted?
Solution 1
If possible, setting up automount ( autofs ) would be the standard way to do this. It might already be in your distribution (comes with CentOS / Redhat default install ). Here is a tutorial.
Why use Automount?
Automounting is the process where mounting and unmounting of certain filesystems is done automatically by a daemon. If the filesystem is unmounted, and a user attempts to access it, it will be automatically (re)mounted. This is especially useful in large networked environments and for crossmounting filesystems between a few machines (especially ones which are not always online).
Solution 2
Can you grep /etc/mtab
for the device? grep -c '/mnt/foo' /etc/mtab
if grep outputs '1' then /mnt/foo is mounted.
Solution 3
Use mountpoint
.
mountpoint -q /path/to/nfs/share || mount -t nfs server:/nfs/share /path/to/nfs/share
(I don't know how widespread or portable mountpoint
is; it's provided by the initscripts package on my Debian server.)
Solution 4
In solaris
If your checking that the system where the script is running has a remote filesystem mounted then
ISMOUNTED=`/usr/sbin/mount | grep "^/path/to/mount "`
if [ "$ISMOUNTED" = "" ]
then
mountcommand*
fi
*mountcommand could be /usr/sbin/mount /path/to/mount if there is a corresponding entry in the /etc/vfstab or /usr/sbin/mount remotehost:/remote/path /path/to/mount
Solution 5
Just to throw another idea out there, the df command can tell you the mounted filesystem of a directory. If you throw in the -l
option, you get a pretty easy test to see if a directory is on a local filesystem or not.
$ cd /net/remoteshare
$ df -l .
df: no file systems processed
$ echo $?
1
Related videos on Youtube
Comments
-
DrStalker almost 2 years
In a bourne shell script (#!/bin/sh) how can check to see if a remote NFS share is mounted and, if it is not, mount it? I've got an ugly set of cat, greps and ifs using the output of 'mount' at the moment but it doesn't seem to be doing a reliable job.
-
Admin almost 15 yearsIt would be helpful to see your own effort in solving this. If you have a code that's unreliable, show it here and help us make it reliable.
-
-
derobert almost 15 yearsThat'd be basically the same as what he/she is currently doing, grepping mount's output.
-
beggs almost 15 yearsOk, but why is it not reliable? Bug in the script or problem with mount's output?
-
DrStalker almost 15 years/facepalm. Now that you mention it automount is such an obvious way to approach this!
-
user12096 about 14 yearswhat about greping /proc/mounts? on many sytems this is more up to date than /etc/mtab
-
David Ramirez almost 12 yearsAt least it exists in fedora 17 - and was unaware of it. Thanks!