kkk001
kkk001

Reputation: 31

Inotifywait not work as expected with while loop

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

Upvotes: 1

Views: 1171

Answers (2)

Léa Gris
Léa Gris

Reputation: 19675

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

Upvotes: 1

Zois Tasoulas
Zois Tasoulas

Reputation: 1555

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

let "count=count+1";

This answer can also be useful

Upvotes: 0

Related Questions