Check a samba mount is still available in Linux Bash
Sometimes in shell scripts I need to get files from Samba shares but these can become disconnected for various reasons so it’s always a good idea to check before retrieving data from them.
An easy way to do this is to check whether the share you want to use is mentioned in /proc/mounts which is part of the proc virtual file system. /proc/mounts is not a real file like many end points in linux.
So in my linux bash script I use an if/else/fi entry to check if the Samba share I need is present and do something about it if it isn’t.
if grep -qs '//MYSERVER/MYSHARE' /proc/mounts; then
echo -e "Samba share is ok "
sleep 0.5
else
echo -e "Folder Disconnected, remounting at " $Today
sudo mount -t cifs //MYSERVER/MYSHARE /var/myshare -o vers=2.0,username=myusername,password=mypassword,uid=www-data,gid=www-data,file_mode=0755,dir_mode=0755
sleep 0.5
fi
So at the beginning of the if I use grep -qs (switches suppress output to standard output) on the /proc/mounts device. If a match is found this command will exit with zero status (success).
If the result is anything other than zero the share must have become disconnected. I am reconnecting using the mount command with the type cifs which is the newer linux kernel file system not relying on Samba.
The username and password should be Windows network user with appropriate permissions to access the share.
The echo entries are for logging purposes and the sleep commands are present to give the mount command time to complete it’s task before attempting to access any files. 0.5 seconds is perhaps a bit mean but I haven’t had any issues up to now.