Hi,

I was wanting to write a (ba)sh script to allow me to wait for the detection of a new USB device, and when that device is detected, execute some commands. The scripts are intending to be working on the principle that whenever I plug in a usb device a message containing the words "new" and "USB" is appended to /var/log/messages. I want this program to be running in the background of my computer at all times, so I want one that will take as little cpu power as it can when there is nothing for it to do. I have tried to do this two ways: with read and with tail ./fifo_pipe.

My first attempt looked something like this:

#!/bin/sh
#foo.sh

tail -f /var/log/messages | grep "new.*USB" | ./bar.sh &
disown %
#!/bin/sh
#bar.sh
while true
do
  read
  echo "detected new usb"
done

This did absolutely nothing.

Then I tried this:

#!/bin/sh
#foo2.sh
mkfifo pipe
tail -f /var/log/messages | grep "new.*USB" > pipe &
disown %
while true
do
  tail pipe
  echo "found new USB device"
done

Just as before it did not output anything.
Any suggestions? I do not want to use udev or automount, but use tail -f /var/log/messages

-thanks

Hi Sudo! I've done something similar before to monitor a log for errors, and execute commands based on what it found. Here's an example:

#!/bin/bash
logfile="/var/log/messages"
pattern="ERROR.*xxx"

tail -fn0 $logfile | while read line ; do
  echo "$line" | grep "$pattern" 
  if [ $? = 0 ]; then
    echo "$line"
  fi
done

I hope this helps! I like the pipe idea, but I haven't tried anything like that yet.

That worked well.

My problem was with grep. When I removed grep from that line everything worked as planed.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.