How do I detect new files in a folder with a bash script? I would like to process the files as soon as they are created in the folder. Is this possible to do so or do I have to schedule a script with cron that that check for new files each minute or so?
|
|
You should consider using
In Ubuntu |
|||||||||||
|
|
I prefer incron, as its easier to manage. Essentially its a service that leverages Ex:
You can see a full example here: http://www.cyberciti.biz/faq/linux-inotify-examples-to-replicate-directories/ |
|||
|
|
|
Bash cannot do this easily. You'd have to basically get a list of all the files in the folder and periodically get a new list and compare them to see whats changed. What you're looking for is called inotify. Its built into the linux kernel and you can basically sit there waiting for something to happen at which point inotify comes back and says 'hey, theres a new file called foobar' To accomplish what you want you'd have to switch to something like perl and use Linux::Inotify2 (python probably supports inotify as well, but I'm a perl person). |
|||
|
|
|
I am assuming the target folder (I'll call it You can use the following command:
just to check if the folder is still empty, in fact it will return a 0 if there is no new file (hence the That said a silly if/then test can make the rest of the work:
Of course the Adding a line like the following in your crontab will run the check once a minute and will trigger the
|
|||
|
|
|
Check out the script mentioned in this url . It uses inotifywait to recursively monitor and record file creation events. |
|||||
|
|||||
We're looking for long answers that provide some explanation and context. Don't just give a one-line answer: please explain why you're recommending it as a solution. Answers that don't explain anything will be deleted. See Good Subjective, Bad Subjective for more information. |
|||||
