Auto copy a file to the newly created folder with a specific name in Linux

·

2 min read

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

  1. 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
    
  2. Make the script runnable with chmod +x copier.sh
  3. Keep the script running by using deamon and supervisor

Code Explanation

  1. 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
  2. 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
  3. 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
  4. 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 linux.die.net/man/1/inotifywait