Search code examples
bashinotifyinotifywait

watch multiple directories using inotifywait and run scripts


I have multiple git repositories containing websites. I want to run inotifywait against their cloned local versions in order to monitor for certain file events and automatically run git push and git pull scripts when those events are detected.

So far I've created a script with separate functions for each directory, but only the first function gets called.

  #!/usr/bin/env bash

  dbg() {
  inotifywait -mr -e ATTRIB /path/to/dbg/ |
  while read dir ev file;
  do
  cd /path/to/dbg
  git pull;
  git add .;
  git commit -m " something regarding this website has changed. check .... for more        info";
  git push;
  ssh [email protected] 'cd /path/to/web/root; git pull';
  done;
  }
  dbg;

  website2() {
  same thing as above
  }
  website2;

  website3() {
  same thing as above
  }
  website3;

  .......

  website10() {
  ........
  }
  website10;

How can I structure this bit of code to be more efficient and more important, fully operational, without having to createa and manage 10 separate scripts. I really would like to keep this logic together in one file, I want this to be one module to go towards a greater project.

Please critique my questioning, my grammar, thinking process etc etc. So that I can improve. thank you.


Solution

  • If you logic is the same, you can use bash function to avoid copying. Besides, commit message can also be passed as an argument. try this

    #!/usr/bin/env bash
    
    dbg() {
    dbg_dir=$1
    webroot_dir=$2
    inotifywait -mr -e ATTRIB $dbg_dir |
    while read dir ev file;
    do
    cd /path/to/dbg
    git pull;
    git add .;
    git commit -m " something regarding this website has changed. check .... for more        info";
    git push;
    ssh [email protected] 'cd $webroot_dir; git pull';
    done;
    }
    dbg /path/to/dbg /path/to/webroot1 &  # & will run the command in background
    dbg /path/to/dbg2 /path/to/webroot2 &
    dbg /path/to/dbg3 /path/to/webroot3 &