DEV Community

Bryan
Bryan

Posted on • Edited on • Originally published at devlogbook.com

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

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 https://linux.die.net/man/1/inotifywait

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay