2

I have a main script calling the script to do the monitoring.

I am trying to catch the exception that the log is missing or not accessible anymore.

tail -f is used instead of -F since the logs are named with the current date.

trap may be working but I am not sure what signal tail -f would return if the log being monitored is no longer there.

Otherwise, should I just do a loop checking in the main script checking for [ -r $Log]?

1

I just gave it a try and see what the main problem is here.

If I do a tail -f on an existing file and then remove the file, tail will not notice that at all. The reson is simple: tail -f opens a read-only-file-handle that references the content of the file. Now if the file vanishes, only the meta-directory-entry vanishes. The allocation will be freed, when the last FH closes - which is tail in this case.

So you have to

  • put tail -f into a background-process of its own, remember its PID.
  • Start another process that monitors the existence of the file (in a while-loop every second or something like that)
  • If that monitor sees that the file has gone, it has to signal the PID of the corresponding tail-process - with a signal of your choice - you can use trap within the tail-process.
2

The tail program won't notice that the file has been deleted. You need something else for that. The inotify facility on Linux allows an application to be notified on file events; most other unices have similar facilities. The following command prints a notification when file.log is deleted:

inotifywait -e delete file.log
  • tail -F does notice that the file has been deleted (or created), but I didn't see a way of using it in a script. There is also --max-unchanged-stats, but the man page says: "With inotify, this option is rarely useful". – Paulo Almeida Jul 31 '13 at 7:02
1
$ tail -f blah
tail: cannot open `blah' for reading: No such file or directory
$ echo $?
1

You could test for that when the file does not exist in the first place, but it won't help you if the file becomes inaccessible. A while loop may be better in this scenario:

while [ 1 ]
do
        tail $1
        if [ "$?" != "0" ]
        then
                echo "No access to file"
                exit 1
        fi
done

I got the idea in a Stackoverflow answer. There are alternatives there, but this one is simple.

  • Won't the while loop keeps creating new tail processes? – geledek Jul 31 '13 at 6:08
  • Yes. That's not necessarily a problem, but I think Gilles' solution is the most elegant. – Paulo Almeida Jul 31 '13 at 6:57

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.