Is there a way to rename files inside a folder as they're created?
I could run a cron job every few seconds to do something like...
find . -name "file.*" -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/file.*\$/"file-$(date).*"/)"' _ {} \;
but this seems really cumbersome, cycle-wise...
12 Answers
There's a framework in Linux called inotify which allows a program to register a handler to be called each time a file or a directory changes, so if you're writing a C program you can just use that. Obviously, your program will need to be running when the change occurs.
There is a special daemon called incron which is like "cron for inotify" and is able to run scripts when a file/directory changes. It can be installed with sudo apt-get install incron, then you'll need add a few lines to its configuration file.
Here's a helpful article: Linux incrond inotify: Monitor Directories For Changes And Take Action
If you search synaptic for "inotify" you'll find many more libraries and programs with similar functionality.
4So, using incron, I set it up by running sudo apt-get install incron.
My goal: Allow emails with picture attachments sent to an alias (sendtodropbox.com app) to be automatically copied into my blog's photo repository for posting.
Next I created a simple bash script:
#!/bin/bash
ls photo.JPG | while read a; do mv $a "$(echo "$a" | sed s/"photo$(date +%a%b%d%H%M).jpg"/)"; done
mv photo* ~/Dropbox/Attachments /<photo repo>/I place the script in ~/, then edit the /etc/incron.allow file to include my user name because these scripts and files are all in my home dir. Next I have to edit the incron config file by running incrontab -e.
In here I used ~/Dropbox/Attachments/ IN_MOVED_TO ~/script.sh (I used IN_MOVED_TO because the action of Dropbox placing a file in the Dropbox folder is considered a move)
This is working instantaneously when I email my Dropbox a picture from my phone now. I also tested incron with both root and my user name to make sure it worked, my first test as my user was: incrontab -e add the config: ~/ IN_CREATE touch ~/test, I then go to ~/, and run >foo, and test appears.