How can I set up a script which copies all modified files and subfolders from folder A to folder B using inotifywait?

I have a folder (A) with lots of files and subfolders.

I want to automatically copy only recently created or modified files and subfolders to folder (B). Older files should not be copied.

I want to use inotifywait for monitoring folder (A). For copying perhaps rsync or a similar tool.

How would the script look like?



Use the -r option of inotifywait to watch all the subdirectories. The -m runs infinitely, i.e. doesn't stop watching after the first event.

For rsync, use -R for relative path names. The slash is needed after the target path, otherwise all files would be copied to the root of the target directory.

#! /bin/bash

inotifywait -m -r -e close_write -e moved_to "$source" \
| while read dir event file ; do
    rsync -R "$dir/$file" "$target"/
| improve this answer | |
  • I can't get this to work. It doesn't seem to notice new files or directories. – Vesa Apr 27 '19 at 4:20
  • Also shouldn't it be moved_from source rather than moved_to source or something like that? – Vesa Apr 27 '19 at 4:22
  • You want inotify to tell you when a new file is to source because you then want to copy it to target. When a file is moved from source, maybe you want to delete it from target if it exists there? – choroba Apr 27 '19 at 19:54
  • Ok I assume you're correct about this. No deleting from target. Anyway, I still couldn't get the script to work. – Vesa Apr 28 '19 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.