Skip to content

Instantly share code, notes, and snippets.

@PhrozenByte
Created May 7, 2025 14:19
Show Gist options
  • Save PhrozenByte/da0e61d2ab326ed917722ab353b4c4b5 to your computer and use it in GitHub Desktop.
Save PhrozenByte/da0e61d2ab326ed917722ab353b4c4b5 to your computer and use it in GitHub Desktop.
NetworkManager dispatcher script to start/stop a Systemd unit when a connection's status changes.
#!/bin/bash
# nm-systemd-dispatcher.sh
# Starts/stops a Systemd unit when a connection's status changes to up/down.
#
# Install this script to `/etc/NetworkManager/dispatcher.d/60-systemd.sh` and
# add the following section to your NetworkManager connection config in
# `/etc/NetworkManager/system-connections/*.nmconnection`:
# [user]
# systemd.unit=myservice.service
#
# Copyright (C) 2025 Daniel Rudolf (<https://www.daniel-rudolf.de>)
# License: The MIT License <http://opensource.org/licenses/MIT>
#
# SPDX-License-Identifier: MIT
print_usage() {
echo "Usage:"
echo " ${BASH_SOURCE[0]} <interface> <action>"
}
[ $# -ge 2 ] || { print_usage >&2; exit 1; }
INTERFACE="$1"
ACTION="$2"
[ -n "$INTERFACE" ] || exit 0
[ "$ACTION" == "up" ] || [ "$ACTION" == "down" ] || exit 0
[ -n "${CONNECTION_USER_SYSTEMD__UNIT:-}" ] || exit 0
case "$ACTION" in
"up")
systemctl start "$CONNECTION_USER_SYSTEMD__UNIT"
;;
"down")
systemctl stop "$CONNECTION_USER_SYSTEMD__UNIT"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment