Linux: Mount Windows share with script

Integrate Samba share with shell script in Linux. This is how it works!

I have installed Linux on my laptop on the road. I wanted to mount my NAS shares here, if required. So I wanted to have a small shell script that integrates and mounts the share.

Let’s get started!

Video

Installation cifs-utils

If not yet installed:

sudo apt-get install cifs-utils

mount script

Now we come to the mount script. Simply copy this and adapt it in a text editor of your choice. In the first part we find the configuration, here we enter the name of the share, the mount directory, user name and password.

#!/bin/bash

# Configuration variables
SHARE="//server/share"
MOUNT_POINT="/mnt/samba"
USERNAME="your_username"
PASSWORD="your_password"

# Check if the mount point directory exists
if [ ! -d "$MOUNT_POINT" ]; then
  echo "Creating mount point directory: $MOUNT_POINT"
  mkdir -p "$MOUNT_POINT"
fi

# Mount the Samba share with write access
echo "Mounting the Samba share..."
sudo mount -t cifs "$SHARE" "$MOUNT_POINT" -o username="$USERNAME",password="$PASSWORD",rw,uid=$(id -u),gid=$(id -g),file_mode=0777,dir_mode=0777

# Check if the mount was successful
if [ $? -eq 0 ]; then
  echo "Samba share mounted successfully at $MOUNT_POINT"
else
  echo "Failed to mount Samba share"
fi

The script also creates the folder, if it does not exist, in which the share is mounted.

After saving the file, we make it executable.

chmod +x mount_samba.sh

We can then execute the script and mount the share.

./mount_samba.sh

Unmount Script

We can also create a script to unmount the share. Same procedure.

#!/bin/bash

# Configuration variable
MOUNT_POINT="/mnt/samba"

# Unmount the Samba share
echo "Unmounting the Samba share..."
sudo umount "$MOUNT_POINT"

# Check if the unmount was successful
if [ $? -eq 0 ]; then
  echo "Samba share unmounted successfully from $MOUNT_POINT"
else
  echo "Failed to unmount Samba share"
fi

Here, too, we make the script executable again.

chmod +x unmount_samba.sh

We can then execute the script.

./unmount_samba.sh

Leave a Reply

Your email address will not be published. Required fields are marked *