Watch a directory for new files

In Solaris, and other distros without the "watch" command, use the following code watch for files added to a directory.

#!/bin/bash

while [ 1 ];
do
        watchdir=/var/tmp
	newfile=$watchdir/.newer
        touch $newfile
        find $watchdir -newer $newfile; 
	touch -a -m $newfile;
        sleep 5;
done

I don't see a question raised here!!

No question, sharing the information. I see this come up a lot.

Yup ... and by the way, you can also just use the watch command instead:

man watch

(see -d option and -n option)

1 Like

FYI: os2mac's second post here was in the moderation queue... I approved it just a second before ctsgnb's reply.

you are assuming of course everyone is on your distro:

man watch
No manual entry for watch.

:slight_smile:

You said that, but didn't mention what 'distro' you are on... :wink:

2 Likes

@os2mac

First, as Scott said, you didn't mentionned your distro.

Then, i also mentionned this alternative in case people have it on their distro ... since your point was "sharing the information" about "watching a directory for new file".

... And if we talk about what people "assume" , you assumed that the ".newer" file already exists which may not be the case at the first loop of your code ... :wink:

$ while [ 1 ];
> do
>         watchdir=/var/tmp
> newfile=$watchdir/.newer
>         find $watchdir -newer $newfile; 
> touch -a -m $newfile;
>         sleep 5;
> done
find: "/var/tmp/.newer": Aucun fichier ou dossier de ce type

:smiley:

1 Like

The irony, it burns us when we touches it..

os2mac:

I applaud your desire to help others, but, without exaggerating, your solution is utterly unfit for deployment.

Each iteration of that loop will consume approximately 5 seconds, most of it sleeping while files that will never be detected are created.

If things that do not need to be in the loop are extracted, the situation improves significantly:

watchdir=/var/tmp
newfile=$watchdir/.newer
touch $newfile
while [ 1 ];
do
        find $watchdir -newer $newfile; 
        -->FILES CREATED DURING THIS WINDOW ARE LOST<-- 
	touch -a -m $newfile;
        sleep 5;
done

There is still a race condition between find and touch, but at least now it's only a tiny fraction of each iteration's wall clock run time.

This is much better, and perhaps it's sufficient for personal use, but if a file cannot go unreported, it's still inadequate.

Regards,
Alister

2 Likes

Thanks for the education Obi Wan, I will endevour to follow you're guidance in the future, master. What other foo can you impart upon a lowly Solaris Junkie?