Run script when usb drive is connected

Hi everyone and thanks you to taking the time to read this post.

I’m trying to make my pi running some mpc commands when a usb stick is connected / removed.

this is my udev rule :

ACTION=="add"\
, SUBSYSTEM=="block"\
, KERNEL=="sd?1"\
, RUN+="/home/pi/udev/usbAdd.sh"

ACTION=="remove"\
, SUBSYSTEM=="block"\
, KERNEL=="sd?1"\
, RUN+="/home/pi/udev/usbRemove.sh"

this is my usbAdd script

#!/bin/bash

set -x

exec > /home/pi/udev/error.log 2>&1

sleep 10

echo "updating"
mpc update

while  mpc status | grep -q 'Updating DB'
do   sleep 3
done
mpc --wait clear
mpc --wait add usb
mpc --wait play

and my usbRemove script

#!/bin/bash

set -x

exec > /home/pi/udev/error.log 2>&1

mpc stop
mpc clear
mpc update

The problem is that the add script only works when it’s manually executed.

When its triggered with the udev rule, the mpd database stay empty. I think this is because when the script is executed, the usb volume isn’t fully mounted yet but I don’t have any idea on how to make sure to run the add script when the mount point is ready (see my desperate move with the sleep call…).

thanks you for your help :slight_smile: