Page Body

How to Run a Command When a Removable Drive Is Mounted With systemd

It can be useful to automatically execute a command when a removable drive is mounted to a file system. The systemd initialization system makes this a relatively easy process.

The Use Case

Assume that you have a collection of PDF files on your GNU/Linux system that you want to carry around on a removable drive. You want to be able to read the files anywhere you go, and after you read a file, you remove it from your portable drive.

It may be hard to keep track of what files you deleted, so you create a shell script (e.g., syn_pdfs.bash) that syncs the files between your GNU/Linux system's directory and the removable drive's directory. The script is interactive and requires you to specify which direction you want the sync to go (e.g., to sync from the system to the removable drive, or vice versa).

The full script is available below:

You could manually run the script every time you attach the drive, but it would be nice to have the system automatically detect when the drive is mounted and launch the script for you. systemd can help you with this task.

The Implementation

When you attach a removable drive to a GNU/Linux system utilizing systemd and GNOME, a corresponding .mount unit is created for it. To obtain the name of this .mount unit file, attach the removable drive to your system and run:

systemctl list-units -t mount

Look for the UNIT that corresponds to your removable drive and copy its name (e.g., media-amnesia-rem_drive.mount).

Next, ensure that the ${HOME}/.config/systemd/user/ directory exists and create a .service unit file in it, e.g., syn_drive.service. The .service unit file should have contents like the following:

[Unit]
Description=Sync my PDF files.
Requires=media-amnesia-rem_drive.mount.mount
After=media-amnesia-rem_drive.mount.mount

[Service]
ExecStart=gnome-terminal -- '/home/amnesia/Scripts/syn_pdfs.bash'

[Install]
WantedBy=media-amnesia-rem_drive.mount.mount

Finally, start and enable the new .service unit:

systemctl --user enable --now syn_drive.service

Now, every time you connect your removable drive to the system and GNOME mounts it, a gnome-terminal instance will automatically open and run the sync script. After you choose a sync direction and the sync completes, the script will exit and the gnome-terminal instance will close.

Enjoyed this post?

Subscribe to the feed for the latest updates.