4

Unlike the answer to this question (Can a bash script be hooked to a file?) I want to be able to see content of files that haven't been created yet as or after they are created. I don't know when they will be created or what they will be named. That solution is for a specific file and actually mentions in the question title creating a "hook" to a specific file. My question is different because I don't want to hook anything, and what I do want is not specific to a particular file. My question's title specifies "..as they are created" which should be a clue that the files I am interested in do not exist yet.

I have an application that users use to submit information from a website. My code creates output files when the user is finished. I want to be able to see the content of these files as they are created, similar to the way tail -f works, but I don't know ahead of time what the filenames will be.

Is there a way to cat files as they are created or would I have to somehow create an endless loop that uses find with the -newermt flag

Something like this is the best I can come up with so far:

#!/bin/bash
# news.sh

while true
do
  d=$(date +"%T Today")
  sleep 10
  find . -newermt "$d" -exec head {} +
done

For clarification, I don't necessarily need to tail the files. Once they are created and closed, they will not be re-opened. Existing files will never change and get a new modification time, and so I am not interested in them.

1 Answers1

2

If on Linux, something like this should do what you are looking for:

inotifywait -m -e close_write --format %w%f -r /watch/dir |
  while IFS= read -r file
  do
    cat < "$file"
  done
Graeme
  • 34,027
  • Watching for close_write events and using cat (without &) might be a better approach. – Stéphane Chazelas Feb 26 '14 at 19:42
  • @Stephane I thought about that but then you will catch all files written to. You could do another inotify on the same file, but if it is closed too quick you won't get anything. – Graeme Feb 26 '14 at 19:47
  • @Stephane, why the IFS=? I don't think that is necessary. – Graeme Feb 26 '14 at 19:53
  • tail is not necessary in an answer, I added to my question to clarify – David Wilkins Feb 26 '14 at 20:02
  • 2
    If white space characters (tab and space as in the default value of IFS) are in $IFS, then they'll be removed from the beginning and end of the line. If you want to read a line verbatim, you must always remove the whitespace characters from IFS, the easiest being to set IFS to the empty string. – Stéphane Chazelas Feb 26 '14 at 20:07
  • @David, in that case close_write and cat is the way to go. Only potential problem is if the files are open for a long time and you need to see output before they close. – Graeme Feb 26 '14 at 20:09