[Answer to: “How to execute a script after every systemd automount?”](https://unix.stackexchange.com/a/806542/246626), posted by [TuringTux](https://unix.stackexchange.com/users/246626/turingtux), [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), reproduced here for the purposes of archiving.
---
My requirements were as follows:
**Any time a partition becomes available at `/dev/sdb1`¹, it should be mounted to `/mnt`², and then a script should be executed.**
This is, sadly, not entirely what you needed, as I only care about the first partition on the device, not all, but maybe my solution can be generalized.
Everything was tested on Manjaro KDE, with KDE's automount option disabled in the System Settings.
# Units to create
The units are all stored in `/etc/systemd/system`.
You can give that any arbitrary name, this is just a “normal” systemd service.
```
[Unit]
Description=Execute a script of your choice once the USB stick is mounted
[Service]
Type=oneshot
ExecStart=/home/turingtux/somescript.sh
[Install]
WantedBy=dev-sdb1.device
```
Enable it:
```
sudo systemctl enable --now myservice
```
* You can list all device units to pick the one you want to depend on using `sudo systemctl list-units --type=device --all`.
* See the docs: [systemd.device](https://www.freedesktop.org/software/systemd/man/latest/systemd.device.html).
* For a oneshot service, you can put multiple `ExecStart=` lines if you want to run multiple commands.
# Test that it works
## Mount unit
You can test that it works (if you have a USB stick plugged in) by executing:
```bash
sudo systemctl start mnt.mount
ls /mnt
sudo systemctl stop mnt.mount
```
## Automount unit
Make sure the USB stick is dismounted. Run:
```bash
ls /mnt
```
It should block. Plug in the USB stick. It should take maybe a second, after which the command will return with the contents of the USB stick.
# The idea behind it
The automount unit makes sure that if _something tries to access `/mnt`_, `/dev/sdb1` will be mounted.
The mount unit is a required dependency of the automount unit (this is just how systemd does things).
The service unit, by depending on a device unit, makes sure that if `/dev/sdb1` becomes available, _something tries to access `/mnt`_.
---
¹ This is mostly be equivalent to “any time a USB stick is plugged in”, with a few caveats: Any block storage device counts, so a USB hard drive would also be counted, or if your computer has hot-swappable SATA drives and you plug one in, that would be counted... Also, this assumes that by default, `/dev/sda` is the last existing device (this is the case on many computers, but depending on the amount of preinstalled hard drives, it might be different in your case).