Post your handy utility scripts!

I created this script for use with a systemd user service for accessing a samba share without implementing any system wide changes.

The script - do remember to run chmod +x on the script file


#! /bin/bash
#
# Script for mounting and unmounting a configured samba share
#  Depends on `smbclient` and `gvfs-smb`
#  Customize the variables as needed
#  - Symlinks are located in designated folder (default: $HOME/SMBLinks)
#  - Symlink can be named  (default: $SHARENAME)
#  - Using `-u` argument will unmount and remove the symlink
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# @linux-aarhus - root.nix.dk
#

# MODIFY THESE VARIABLES
# your samba server's hostname or IP address
HOST="my-server"

# the share name on the server
SHARENAME="my-share"

# symlink name
LINKNAME="$SHARENAME"

# symlink is placed in this folder
SYMLINKS="$HOME/SMBLinks"

# /END MODIFY

SCRIPTNAME=$(basename "$0")
VERSION="0.2"

# check argument $1
if [[ "$1" == "-u" ]]; then
    # remove symlink
    rm -f "$SYMLINKS/$LINKNAME"
    # unmount share
    gio mount -u "smb://$HOST/$SHARENAME"
    exit
elif [[ $1 != "" ]]; then
    echo ":: $SCRIPTNAME v$VERSION"
    echo "==> invalid argument: $1"
    echo "Usage: "
    echo "  mount SMB : $SCRIPTNAME"
    echo "  umount SMB: $SCRIPTNAME -u"
    exit 1
fi

# mount command
gio mount "smb://$HOST/$SHARENAME"

# easy reference to gio mount point
ENDPOINT=/run/user/$UID/gvfs/''smb-share:server=$HOST,share=$SHARENAME''

# create the subfolder
if ! [ -d "$SYMLINKS" ]; then
    mkdir -p "$SYMLINKS"
fi

# use --force argument to suppress warning if link exist
ln -sf "$ENDPOINT" "$SYMLINKS/$LINKNAME"

:spiral_notepad: Note:

  • The user service is assuming the above script is located in the service folder.
    Adjust naming accordingly.
  • The service file depends on the credentials has been stored in your keyring.
    Open your file manager’s location bar and input
    smb://samba-server/my-share
    
    Then when prompted store your credentials.
    /home/$USER/.config/systemd/user/gio-mount-share.sh
    
[Unit]
Description=GIO mount smb share-name

[Service]
Type=oneshot
ExecStart=/home/%u/.config/systemd/user/gio-mount-share.sh
ExecStop=/home/%u/.config/systemd/user/gio-mount-share.sh -u
RemainAfterExit=true

[Install]
WantedBy=multi-user.target