5

Is there any way to copy the file in Unix as soon as it is created? I have one location where files will be created in different timings.How can I copy the files automatically using shell script to some other location in Unix?

1

2 Answers 2

5
inotifywait -e close_write --format "%f" --monitor . |
  while IFS= read -r line
  do
    #cp "$line" destination/ #this would not replicate directories
    tar cf - "$line" | tar -C destination/ xf - #this should replicate directories
  done

should do the trick, unless the number of files in your directory (I'm using . for the current directory) exceeds your system's limit for inotify watches (fs.inotify.max_user_watches, as coteyr mentions).

10
  • 2
    Also important to be aware of the file watch limit (fs.inotify.max_user_watches) I hit that limit all the time using inotify.
    – coteyr
    Jun 8, 2015 at 10:44
  • Thank you guys very much for the comments. I've incorporated both into the answer. I believe --monitor switch along with close_write should make it reliable. Jun 8, 2015 at 11:38
  • Thanks a lot for the answer.But, I do not have rsync installed on my linux machine.Is there any other way to do this?
    – M.Nehru
    Jun 8, 2015 at 11:52
  • Install it if you can. rsync is useful. But I believe there is. Give me a few seconds. Jun 8, 2015 at 11:53
  • Do you have tar or cpio? Jun 8, 2015 at 11:54
0

You can't really copy files the instant they are created with a shell script alone. Three solutions that come to mind.

  1. rsync with cron - It's simple, standard, and easy. Once every so often ( one time an hour) you run rsync against the directory. Huge structures can be synced in seconds, depending on the amount of changes.

  2. Gluster or similar. Depending on needs.

  3. Just use a symlink.

3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .