If we use the tail command we can listen for events representing changes to the files length (in bytes).

I am looking for a way to listen for events when the content of the file changes but the length is the same. Specifically, looking to listen for changes to the first or second line of the file.

(We might expect that the head command can do this, but it does not seem like the head command can listen for changes, it merely grabs the beginning of content.)

Does anyone know if it's possible to listen for changes to a file's content (the beginning of the file specifically)?

Note there is a process appending data to the file and another process reading and removing the first line of the file.

I am interested in independently listening for changes to the head of the file, but I don't want to capture, or I want to be able to filter out, events that append to the file.

  • 3
    Are you searching for a posix portable solution? Which O.S. are you using? There are various ways to do this but they are O.S. specific. E.g. inotify on linux. – andcoz Jan 30 '17 at 9:08
  • ideally something that works on mac and linux, I guess – Alexander Mills Jan 30 '17 at 9:16
  • however maybe inotify doesn't work out of the box on a mac – Alexander Mills Jan 30 '17 at 9:19
  • "Listening" implies a daemon process actively running in the background. I recommend against daemonizing a shell script loop. – Wildcard Jan 31 '17 at 5:02
  • @Wildcard agreed - I am looking for an evented (non-polling) approach. If I cannot find an evented system tool, I will have to implement my own which is not that bad but would rather using existing if possible. I believe that inotify / inotifywait should be able to do this. – Alexander Mills Jan 31 '17 at 5:20

Perhaps something like this:


while true; do
    diff -q <(head -n 1 fileA.txt) <(head -n 1 fileB.txt)
    sleep 5

Given these two files (fileA.txt and fileB.txt):

cat fileA.txt fileB.txt 


When I change the first line in fileA.txt:

cat fileA.txt 

I get this output from the script:

Files /dev/fd/63 and /dev/fd/62 differ
Files /dev/fd/63 and /dev/fd/62 differ
Files /dev/fd/63 and /dev/fd/62 differ
Files /dev/fd/63 and /dev/fd/62 differ

If I change the second line, nothing happens in the script, it just keeps looping:

cat fileA.txt 

Tested with Mac OS X 10.11.6 and:

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
Copyright (C) 2007 Free Software Foundation, Inc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.