Script not working when evoked by udev rule

血红的双手。 提交于 2019-12-12 03:34:54

问题


I am a Linux Mint user and I am trying to write a rule, that execute a script when I plug in the usb. The #!/bin/sh script, does not succeed to access the USB (even with a normal cd) while if I run the same script from command line, it works perfectly.

The rule I created for that purpose is:

ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="058f", ATTR{idProduct}=="6387", RUN+=="/home/dario/bin/backup_usb"

where the backup_usb for instance looks like:

#!/bin/sh
sleep 10
cd /media/dario/ 
echo " I am now in: $(pwd)" >> /home/dario/bin/log.log
cd /media/dario/DARIO_USB/  # That's the device just plugged in.
echo " I am now in: $(pwd)" >> /home/dario/bin/log.log

The output is:

I am now in: /media/dario/ 
and now in: /

while I was expecting:

I am now in: /media/dario/ 
and now in: /media/dario/DARIO_USB/

I would be very grateful for any help.

(This is the edited version of my question)


回答1:


First, your rule is wrong. Consider something like:

ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="058f",
ATTR{idProduct}=="6387", RUN+="/home/dario/bin/backup_usb"

Second: Kill the sleep 10. If udev is running scripts in order and waiting for each to finish before running the next, it can potentially block any subsequent script (such as the one doing the mount), preventing it from happening at all. We're going to do this differently, putting the polling in the background:

#!/bin/bash
#      ^^^^ - has to be bash, as the C-style for loop syntax used below is a bashism
#             ...as is the [[ ]] construct.

exec </dev/null >/home/dario/usb.log 2>&1
set -x
cd /media/dario || exit
(
  for ((retries=0; retries<10; retries++)); do
    [[ -d DARIO_USB ]] && grep -q -e DARIO_USB /proc/mounts && continue
    sleep 1 # retry
  done
  cd DARIO_USB || exit
  echo "SUCCESS"
) &


来源:https://stackoverflow.com/questions/35045496/script-not-working-when-evoked-by-udev-rule

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!