… has too many hobbies.

Using systemd to keep an SMB share mounted

It's possible to use systemd to keep a SMB share mounted and retry it after the mount fails. This template-based approach scales relatively easily to multiple mounts.

Create the retry service template

In /etc/systemd/system/mount-retry@.service:

[Unit]
Description=Retry mounting %i
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/mount-retry.sh %i
Restart=on-failure
RestartSec=30s
# Retry indefinitely
StartLimitIntervalSec=0

[Install]
WantedBy=multi-user.target

Create the mount-retry.sh script

In /usr/local/bin/mount-retry.sh:

#!/bin/bash
set -euo pipefail

MOUNT_NAME="$1"
# Convert systemd unit name to mount path
MOUNT_PATH=$(systemd-escape --unescape --path "$MOUNT_NAME")

echo "Monitoring mount: $MOUNT_PATH"

while true; do
    if ! mountpoint -q "$MOUNT_PATH"; then
        echo "$(date): $MOUNT_PATH not mounted, attempting mount..."
        systemctl start "${MOUNT_NAME}.mount" || true
    fi
    sleep 60
done

Make it executable:

sudo chmod +x /usr/local/bin/mount-retry.sh

Enable it for each mount

For e.g. a mount at /mnt/share, first get the name for the mount:

systemd-escape --path "/mnt/share"
# output: mnt-share

Then enable & start the retry service for that mount:

sudo systemctl enable mount-retry@mnt-share.service
sudo systemctl start mount-retry@mnt-share.service