2

I have a Raspberry pi b with an SD card reader connected to one of the USB ports. I would like to automatically process files as soon as an SD is inserted. Is there a way to somehow register a program to execute when a new USB disk is detected?

I basically want to use the RPI as a smart SD reader, so the SD reader will be fixed on the one USB port. And I want IoT like behavior with no user interaction ( other than inserting the SD ).

I am trying to avoid an infinite loop checking when one of the /media/usb? directories become valid.

I am new at RPI and not a low lever Linux guy, so any direction will help. Thanks,

dkarchmer
  • 121
  • 4

1 Answers1

2

Assuming you have no other disks plugged in, you could use a very simple python script. Something like:

#foo.py
import os
import time
while True:
    disks=os.system("ls /dev") #checks /dev for a disk, the first disk is always listed as /sda and /sda1
    if "sda1" in disks:
        os.system("sh YOURPROGRAM.sh") #you can put whatever command/program you want it to execute when the drive it mounted here
    time.sleep(0.5) #waits half a second before beginning the next loop, helps reduce strain on the CPU

You would have to run this script using sudo because it needs root privileges to mount disks. sudo python foo.py would work fine.

Unfortunately there is no way to avoid an infinite loop here that I know of, but checking /dev instead of /media might be easier because it does not require the disk to be mounted.

No matter where the disk is automounted, the device will always show up in /dev/sda and /dev/sda1 assuming it is the first drive put into the Pi.

Patrick Cook
  • 6,365
  • 8
  • 38
  • 63