When I need to detect file changes and do something other than what tail -f filename
does, I've used inotifywait
in a script to detect the change and act upon it. An example of use is shown below. See man inotifywait
for other event names and switches. You may need to install the inotify-tools
package, for example via sudo apt-get install inotify-tools
.
Here's the example script, called exec-on-change
:
#!/bin/sh
# Detect when file named by param $1 changes.
# When it changes, do command specified by other params.
F=$1
shift
P="$*"
# Result of inotifywait is put in S so it doesn't echo
while S=$(inotifywait -eMODIFY $F 2>/dev/null)
do
# Remove printf if timestamps not wanted
printf "At %s: \n" "$(date)"
$P
done
In two consoles I entered commands as follows (where A> means entry in console A, and B> means entry in console B.)
A> rm t; touch t
B> ./exec-on-change t wc t
A> date >>t
A> date -R >>t
A> date -Ru >>t
A> cat t; rm t
The following output from cat t
appeared in console A:
Thu Aug 16 11:57:01 MDT 2012
Thu, 16 Aug 2012 11:57:04 -0600
Thu, 16 Aug 2012 17:57:07 +0000
The following output from exec-on-change
appeared in console B:
At Thu Aug 16 11:57:01 MDT 2012:
1 6 29 t
At Thu Aug 16 11:57:04 MDT 2012:
2 12 61 t
At Thu Aug 16 11:57:07 MDT 2012:
3 18 93 t
The exec-on-change
script terminated when I rm
'd t
.