We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,617 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

read from pipe: waiting until data is fed into pipe.

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

2
Contributors
2
Replies
4 Days
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
Sudo Bash
Light Poster
35 posts since Dec 2010
Reputation Points: 10
Solved Threads: 2
Skill Endorsements: 0

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.

Gromit
Posting Whiz in Training
225 posts since Sep 2008
Reputation Points: 50
Solved Threads: 35
Skill Endorsements: 0
Question Answered as of 1 Year Ago by Gromit

That worked well.

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

Thanks!

Sudo Bash
Light Poster
35 posts since Dec 2010
Reputation Points: 10
Solved Threads: 2
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0581 seconds using 2.65MB