We have a file readme.txt in /home/
and want it to be copied over to all new folders created within /home/johndoe/
with names junk or secret
Requirement
Have inotifywait installed: sudo apt install inotify-tools
Script
-
Create a bash file copier.sh with the contents below
#!/bin/bash inotifywait -m -r -e create,move ~/johndoe | while read dir op file do if [[ $op == "CREATE,ISDIR" && $file == 'junk' || $file == 'secret' ]] then cp ~/readme.txt "${dir}/${file}/readme.txt" elif [[ $op == "MOVED_TO,ISDIR" && $file == 'junk' || $file == 'secret' ]] then cp ~/readme.txt "${dir}/${file}/readme.txt" else : fi done
Make the script runnable with
chmod +x copier.sh
Keep the script running by using deamon and supervisor
Code Explanation
-
inotifywait -m -r -e create,move ~/johndoe
-
-m
: keep the script running after 1 time -
-r
: recursively watch all folders -
-e
: events to watch for -
create,move
create is when the file/folder is created, move is used when renaming a folder -
~/johndoe
: folder being watched
-
-
do if [[ $op == "CREATE,ISDIR" && $file == 'junk' || $file == 'secret' ]]
- Only do it when a directory is created and when the directory names are either junk or secret
-
elif [[ $op == "MOVED_TO,ISDIR" && $file == 'junk' || $file == 'secret' ]]
- Only do it when a directory is renamed and when the directory names are either junk or secret
-
cp ~/readme.txt "${dir}/${file}/readme.txt"
- Copy the readme.txt from home directory to the newly created directory
Notes
The default maximum is 8192; it can be increased by writing to /proc/sys/fs/inotify/max_user_watches
.
Learn more from https://linux.die.net/man/1/inotifywait
Top comments (0)