manoj kumar
manoj kumar

Reputation: 1

How to get event of file created/copy in a folder in CentOS?

I need to write a script in CentOS, which will run in background. This script need to check whether a file name "status.txt" has been created in /root/MyFile folder on not. If that file is created, an event should be captured by my script.

What code snippet I should write in my script, so that it gets event that the txt file has been created in a folder?

Any help is greatly appreciated.

Upvotes: 0

Views: 311

Answers (2)

Igor Chubin
Igor Chubin

Reputation: 64563

The simplest solution:

while true; do
do
  [ -e "/root/MyFile/status.txt" ] && { echo file is created; break; }
  sleep 1
done

Instead of echo file is created you can write the commands you want to execute.

You can to the same with inotify:

inotifywait --format '%f' -m /root/MyFile 2> /dev/null | while read file
do
  [ "$file" = status.txt ] \
  && [ -e "/root/Myfile/$file" ] \
  && { echo file is created ; break; }
done

This that solution has that advantage that you will get the action instantly, as the file will be created. And in the first case you will too wait for the second. The second advantage, that you need to poll the filesystem every second.

But this solution has disadvantages also:

  • it works only on Linux;
  • you need relatively modern kernel;
  • you need to install inotify-tools;
  • if you create many files before status.txt will be created, you make many additional comparison operation.

Resuming:

I think, you need the first solution.

Upvotes: 1

Konstantin V. Salikhov
Konstantin V. Salikhov

Reputation: 4653

If your kernel is newer than 2.6.13 you could use inotify mechanism to achieve your goal. Install package inotify-tools and write the script that will watch for your file, using provided examples

Upvotes: 0

Related Questions