Configuring USB notifications on Linux

If you want to receive a small notification as soon as a USB storage device is plugged in or plugged out. You're in the right place

Your system detects a USB device upon connection or disconnection using an utility named udev. udev allows for defining rules which can allow a user to perform a specific task when a USB device is connected or disconnected. This can be combined with notify-send to send notifications to a user as soon as a USB device is connected or disconnected

1. Creating a udev rule

Below is a rule file, which will trigger two scripts depending upon the connection or disconnection of a USB device

ACTION=="add", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk",  RUN+="/usr/local/bin/usb-notify-add.sh '$env{ID_MODEL}'"
ACTION=="remove", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk",  RUN+="/usr/local/bin/usb-notify-rem.sh '$env{ID_MODEL}'"

save this as 99-usb-notify.rules file under /etc/udev/rules.d/.

2. Configuring the scripts

Below are the scripts:

#!/bin/bash
DEVICE_NAME=${1:-"Unknown USB Device"}

USER_ID=$(id -u <your-username>)
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$USER_ID/bus

sudo -u <your-username> DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS /usr/bin/notify-send "USB Connected" "Device: $DEVICE_NAME"
#!/bin/bash
DEVICE_NAME=${1:-"Unknown USB Device"}

USER_ID=$(id -u <your-username>)
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$USER_ID/bus

sudo -u <your-username> DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS /usr/bin/notify-send "USB Disconnected" "Device: $DEVICE_NAME"

Save both the scripts under /usr/local/bin and make them executable with chmod

3. Reloading the udev rules

Once all the files have been saved. Reload udev rules as follows:

sudo udevadm control --reload-rules
sudo udevadm trigger

And just like that, you've setup USB notifications. Give it a try! Plug in a USB device and check whether your system sends your a notification with the name of the USB device.