Threads in BASH? Try a TRAP!

I needed a way to stop monitoring the old one and instantly start monitoring the new one.

I had a situation where I needed to monitor a file using "tail -f" for some particular information on a log file that would fill and begin logging under a different name. The filename would always be something like this:

YYYYMMDD.dat
for example 20080821.dat

When the day changes or the log overturns, a new file is created with the new name. For example, if on the starting day, the file is 20080821.dat the next one may be 20080822.dat. My problem was this, when the new filename was created, I needed a way to stop monitoring the old one and instantly start monitoring the new one. Have you ever came across this scenario? Here's a little trick.

Try this:

#!/bin/bash

trap 'myfilename' USR1

myfilename()
{
   echo "midnight, searching new file..."
   filename="f$j"
   : $(( j++ ))
}


j=0
i=0
myfilename

while :
do
   echo "reading file $filename..."
   sleep 1
   : $(( i++ ))
   # check for midnight
   if [ $(( i%5 )) -eq 0 ]
   then
      echo "suicide ;-)"
      kill -USR1 0
   fi
done

Of course, you can always try 'tail -F' option! But, for me, that was after I realized I could just do that instead! But, hey, you live and learn. And if it is available, you can also use 'multitail'.


Peace be unto you. Thank you for visiting!