Categories

 

March 2010
M T W T F S S
« Sep    
1234567
891011121314
15161718192021
22232425262728
293031  

Bash script to automate mounting and unmounting of nfs shares

This is a small script I wrote that automates creating a directory for the mount point and then mounts the nfs share on that diretory. It also accommodates removal when needed and unmount’s the nfs share and removes the directory that was created.

Notes:

Caution: The script assumes the nfs share is not an existing directory on the local machine. It uses the same mount points on the the local machine as the remote machine.

All mount points are located in /media. I did this to keep in unison with Ubuntu.

This was convenient for me but may not play well on other setups. Simply ask and I can modify the script to accommodate different setups easily. You’re also welcome to change it yourself ;)

Before using this script, you should make sure that your nfs shares are setup correctly and functioning without this script.

Line 22: Replace this with your username:group on your local machine

Lines 13 & 24: Replace x.x.x with your local C class. EX: 192.168.1

Usage:

Make sure the script is executable with chmod +x

Mounting

./filename 100 folder

  • filename is self-explanatory I think.
  • 100 is the last octet of the IP address that the nfs share is located on
  • folder is the remote mount point and local mount point for mounting

Unmounting

./filename u folder

  • u simply means unmount
  • folder is the mount location on the local machine
#!/bin/bash

# MOUNT: ./mnt 100 folder
# UNMOUNT: ./mnt u folder

if [ $1 != "" ] && [ $2 != "" ]; then

  DIR=/media/$2
  EXISTMOUNT=`sudo cat /etc/mtab | grep $DIR`;
  EXISTDIR=`ls /media/ | grep $2`;

  if [ $1 != "u" ]; then
    EXISTREMDIR=`showmount -e 10.0.0.$1 | grep $DIR`;
  fi

  if [[ "$EXISTMOUNT" != *$DIR* ]] && [ $1 != "u" ]  &&
     [[ "$EXISTREMDIR" = *$DIR* ]]; then
    
    echo "Creating: $DIR"
    sudo mkdir $DIR
    sudo chown username:group $DIR
    echo "done."
    echo "Mounting: $DIR"
    sudo mount 10.0.0.$1:$DIR $DIR
    echo "done."
  
  fi
  
  if [ "$EXISTDIR" = $2 ] && [ $1 = "u" ]; then
    
    echo "Unmounting: $DIR"
    sudo umount $DIR;
    echo "done."
    
    # failsafe directory removal
    EXISTMOUNT=`sudo cat /etc/mtab | grep $DIR`;
    if [[ "$EXISTMOUNT" != *$DIR* ]]; then
      echo "Removing: $DIR"
      sudo rmdir $DIR
      echo "done."
    fi
    
  fi
  
fi

You must be logged in to post a comment.