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.
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?
Can you grep
/etc/mtab
for the device?grep -c '/mnt/foo' /etc/mtab
if grep outputs '1' then /mnt/foo is mounted.Use
mountpoint
.(I don't know how widespread or portable
mountpoint
is; it's provided by the initscripts package on my Debian server.)In solaris
If your checking that the system where the script is running has a remote filesystem mounted then
*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
You may be able to do something with stat. The "device" field will be different across different filesystems. So, assuming you want to see if
/mnt/foo
is mounted, you'd compare the output ofstat -c%d /mnt/
tostat -c%d /mnt/foo/
. If the device is different, something is mounted there.When it comes down to it, shell programming is about plugging together small discrete tools using pipes to produce some kind of compound utility. A utility that did what you're asking for in a "smart" way wouldn't really match the Unix philosophy.
If you want to do it more intelligently, you might want to look at doing this in Perl or Python or C, where you can use the library functions to talk to the portmapper to get information about mounted filesystems as a data structure. You can then intelligently perform the tasks to change the current state to the state you want.
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
A few suggestions:
If your distribution has an RC script to handle NFS mounts then it would be prudent to use or it check it's status. You can run into trouble if you incorrectly assume that services such as
portmap
andstatd
are already started.It's often more reliable to use
/proc/mounts
in favour of output frommount
or the possibly out-of-date content of/etc/mtab
.Use
grep -qs
and check the return code to determine whether a mount is present or not.Assuming that all of the NFS mounts listed in
/etc/fstab
should be mounted then you can mount them universally withmount -a -t nfs,nfs4
. Anything already mounted will be ignored.