Kian Cross
Kian Cross

Reputation: 1818

How can I have a script that runs when a specified disk s unmounted in Linux?

I am trying to write a script that when I run it, checks to see if a specified drive is mounted, if it is, then it does nothing and the script continues, otherwise it mounts the disk.

The pseudo code for it is:

if dev/disksa1 is mounted at /media/server:
    print ""
else:
    mount dev/disk/sa1 at /media/server

The actual code I have done to try and achieve this is. This was recommended in another post:

if grep -qs 'MinecraftServer' /media/<username>/MinecraftServer/MinecraftServer; then
    echo "Disk already mounted, server boot will continue"
else
     mount /dev/sda1 /media/kiancross/MinecraftServer
fi

For some reason though, no matter what it always remounts the disk, even if it is already mounted.

Not too sure why this is happening, can anyone point me in the right direction?

Upvotes: 0

Views: 492

Answers (2)

Sam Wahid
Sam Wahid

Reputation: 126

If you are looking to see what drives are already mounted, that information is usually updated in /etc/mtab. My solution to mount an unmounted drive is:

if grep --quiet 'drive_name' /etc/mtab; then
   echo "already mounted"
else
   /bin/mount /path/to/mount/point
fi

Of course, the mount must already be listed in /etc/fstab for /bin/mount to work in this fashion.

So, in your specific case, I would suggest:

if grep -qs 'MinecraftServer' /etc/mtab; then
    echo "Disk already mounted, server boot will continue"
else
     mount /dev/sda1 /media/kiancross/MinecraftServer
fi

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798446

Most Linux distros (as well as the mount(8) command) look for a file called /etc/fstab for information on filesystems that should be mounted. Adding an entry in there with the correct options will cause the system to mount the filesystem on boot. See the fstab(5) man page for details.

Upvotes: 1

Related Questions