1

I would like to run the number of modify option in the monitored directory and when 3 modify event happened. I would like to run an command.

I have tried the code as shown below, however count variable is not increasing even though modification event happened.

#!/bin/bash
count=0
while :
do
    { inotifywait -m -q -e modify /home/testDir& let count="$count + 1"; } || exit 1
    if [ "$count" -eq "3" ]; then
        #Do something
        count=-250
    fi
done
kkk001
  • 31
  • 2

2 Answers2

1

There several issues with your script and the inotify use:

inotifywait -m -q -e modify: -m: monitor without exiting, so it will never exit, and never print-out anything -q: will not print-out anything -e: the modify event does not apply to directories but to files within it

{ inotifywait -m -q -e modify /home/testDir& let count="$count + 1"; } || exit 1

will launch inotifywait in the background, immediately add 1 to count and continue

let count="$count + 1: Is very obsolete. use count=$((count + 1)) instead.

A fixed version:

#!/usr/bin/env sh

count=0
while :; do
  {
    inotifywait -qe 'modify' /home/lea/t/testDir || exit 1
  } >/dev/null 2>&1 
  count=$((count + 1))
  if [ "$count" -eq "3" ]; then
    echo 'Do something'
    count=-250
  fi
done
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • Thank you for your great answer, it works as expected. However, I would like to kill the specific process when the `count` is equal to 3. However, when I kill the process with kill command it does not kills immediately. Do you think `inotifywait` is not fast enough to kill the process immediately after the `modify` `action` happened. – kkk001 Jan 31 '21 at 21:01
  • Depend what process you want to kill once reaching 3. Do you mean breaking out of the while loop? If so just use `if [ "$count" -eq "3" ]; then .. break` – Léa Gris Jan 31 '21 at 22:01
  • @kkk001 Depending on something happening fast enough ("immediately") is almost never safe. Even if you get it to work now, it's likely to randomly fail, often when something seemingly irrelevant changes. The standard term for this is ["race condition"](https://en.wikipedia.org/wiki/Race_condition#Software), and it's basically considered a bug and a sign that you really should be doing things differently. – Gordon Davisson Jan 31 '21 at 22:07
0

The issue is in the let statement. You can replace it with:

let "count=count+1";

This answer can also be useful

Zois Tasoulas
  • 1,242
  • 1
  • 11
  • 23