HOWTO: Automatically run a command when USB-disk is plugged in
Post by goebbe » Tue Oct 08, 2024 3:17 am
The following describes how to run commands automatically when a specific USB-device is plugged in.
This howto has been tested on Linux Mint 22 (based on Ubuntu 24.04). The howto uses systemd. No special privileges are required.
Possible use case: Run a backup script automatically, as soon as you plug in a specific USB-drive.
Howto run a script or a command automatically when a specific .mount unit becomes available:
- Plugin the USB device - by default the device is mounted. - In the terminal: List all .mount units of the current user to identify the .mount-unit of the USB-device:
systemctl --user list-units -t mount
- Identify the .mount unit for your USB-device. For example, for a USB-device with label “yourUSBlabel”, the following .mount-unit should be available: media-yourusername-yourUSBlabel.mount
- In your text editor: Create/ Place the following Systemd .service-file in ~/.config/systemd/user/auto-usb-command.service Adapt/ edit the .service file: yourusername, yourUSBlabel, and yourcommand should be replaced accordingly.
[Unit] description=Runs command automatically when the specified usb .mount-unit becomes available [Service] Type=oneshot ExecStart=/bin/bash -c '/pathto/yourcommand' [Install] WantedBy=media-yourusername-yourUSBlabel.mount
Important: The user has to be able to run /pathto/yourcommand in the terminal. Scripts / commands have to be executable.
- In the terminal: Start the new service:
systemctl start --user auto-usb-command.service
- Enable the service:
systemctl enable --user auto-usb-command.service
Now, whenever you plugin/ mount your USB-device, the specified command will run.
- Finally, after the command has finished, unmount/ safely remove your USB-device.
Maintenance: Useful terminal commands
Check the status of the new service:
systemctl status --user auto-usb-command.service
After changing the .service file, one has to reload:
systemctl --user daemon-reload
Detailed Systemd logs:
journalctl --user -xeu auto-usb-command.service