DEV Community 👩‍💻👨‍💻


Posted on • Updated on • Originally published at

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

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


Have inotifywait installed: sudo apt install inotify-tools


  1. Create a bash file with the contents below

    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 :
  2. Make the script runnable with chmod +x

  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


The default maximum is 8192; it can be increased by writing to /proc/sys/fs/inotify/max_user_watches.

Learn more from

Top comments (0)

Create an Account!

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.