Blog

How to run a script when a filesystem gets mounted on Linux

I wanted to run a script when a filesystem gets mounted on my Ubuntu server. I thought this would be a common task but it took me a while to find the answer. Some people suggested using udev, but udev responds to device changes. If you're trying to trigger something like a backup when you plug in a USB drive, udev is the way to go. But it's no use if your device is always connected but not always mounted.

When my server starts, /home isn't mounted automatically. /home's on an encrypted filesystem, and the system runs without a keyboard and monitor, so I want it to boot up normally without /home and I'll mount it the next time I login. When /home becomes available, it should start a media server and NFS sharing.

It's not well documented, but it's easy under Ubuntu. You need to use upstart and create an init script. These live in /etc/init/ and can have any name ending in .conf. You can either write your script directly in the init script, or call another script elsewhere. As I only had a couple of tasks to perform the behaviour's more obvious if it's in the init script. Here's what mine looks like:

# mounted-home - Trigger actions when home becomes available. 

description "Trigger actions when /home becomes available." 

start on mounted MOUNTPOINT=/home 

task 

script
    /etc/init.d/forked-daapd restart
    service nfs-kernel-server restart   
end script

You could also write a complementary script that stops these things when the home directory is unmounted, but I don't normally unmount my home dir and there's no harm in running this script repeatedly – the restart command will start it if it's stopped, or bounce it if it's already running.