Check for a New Directory

Well, I know I could use a cron job to check if a new directory is made. However, I know that it won't happen like every 5 minutes and would be waste of resources. I was wondering is there a better way to check if a new directory is made in a certain folder without a cron job. I do not want it to check like every 5 minutes or so. I want it to act only when a new directory is made as I plan to run another script once this script knows that a new directory is made. Or if I could somehow know when mkdir command is run. It would helpful.

Thanks for your help.

If you install the inotify-tools package you can run the inotifywait command something like this:

inotifywait -e create /home/you/somedir

It will sleep until either a file or directory is created in the specified directory and exits. You could put it in a loop and just let it run forever. You can also specify a timeout.

I never used the inotify-tools package before, but I luckily had it already installed for some reason (Fedora), and I just stumbled upon it. It looks so interesting that I think I'm going to have to think up a reason to use it.

Easy solution.

Locate where is your mkdir and then (in this case /bin directory)

cd /bin
mv mkdir mkdir.real
#!/bin/sh
#mkdir my own

domylog()
{
   echo "$(date '+%Y%m%d%H%M%S') PID:$$ USER:$LOGNAME mkdir $*" 
}

/bin/mkdir.real $*
stat=$?
[ "$stat" = 0 ] && domylog $* >>mylog 2>&1  && exit 0  # ok
# some error
domylog "error" $* >>mylog 2>&1
exit $stat

---------- Post updated at 07:56 PM ---------- Previous update was at 07:55 PM ----------

chmod a+rx mkdir

But remember = some day you install system update = new mkdir ...

Thanks kshji. Yea, I didn't use your method. I will probably forget and then will be like why it is not working. ^^" Considering, the upgrades will not happen regularly. So, that was an issue. :stuck_out_tongue: However, maybe I can use the same trick for something else. ^^

Thanks KenJackson. Yea, that did the trick. I used -m option in the inotifywait rather than do the while loop. If you made new directories like 3 at a time then it would not work; however, -m did the trick. ^^ Plus, I was able to use it for other events too. So, it was a pretty good utility for me.