share
Unix & LinuxHow can set up a directory listener to copy a file
[0] [1] WireInTheGhost
[2020-04-18 14:31:17]
[ linux shell-script file-copy ]
[ https://unix.stackexchange.com/questions/580919/how-can-set-up-a-directory-listener-to-copy-a-file ]

I would like to create a Bash script that will sit and listen to a directory and when a new directory or file is added it will recursively copy each file to another location. For example:

I can not install inotifywait. Is this possible? Thanks

(2) is there a reason why you cannot get inotifywait ? - Luuk
Seconded. inotifywait (or something related, such as incrontab) is the obvious solution here - Chris Davies
Its just not available on the system im using. I have been trying to do it with a while loop using the watch command but cant seem to get it right - WireInTheGhost
Show the code with which you tried..... And what kind of linux system is not capable of installing a package which contains inotifywait ? - Luuk
How do you plan to deal with a new file that is created, but has not finished being written when you notice it is available? You are likely to get partial files frequently. - Paul_Pedant
I dont have the necessary permissions to install on the system. I have been using this if [ $(ls -1A $inPath | wc -l) -gt 0 ] ;then cp -r $inPath $outPath; in a while loop. But it requires you to know how many files in the directory to begin with. - WireInTheGhost
(1) So get your sysadmin to install the package. - Shawn
A while loop with no sleep will keep one of your CPUs 100% spinning all the time. With some sleep, you'd get polling, which in turn is better accomplished with cron (or equivalent). Also, are you only interested in top-level new directories? What about changes inside them? Should a new file in an existing directory trigger a copy? Finally, should files and directories be copied even if they already exist on the destination? Please, edit new information into your question instead of including it in comments. - fra-san
[+1] [2020-04-18 21:06:37] Hades

What you could do is have a cronjob that runs every hour, which uses a function like below, of courseyou could use a different time.

find /home/user/ --mmin -60 -exec echo This file changed: {} \;

This will output every file that was modified in the time given, for the example above 60 minutes.

This is a example I came up with. It copies the directories where changes happened, it only copies the root upper most directory so its not extremely efficient.

find /home/name/* -maxdepth 0 -mmin -60 -exec cp -r {} /some/other/dir/ \;

1