6

So I'm doing a simple inotifywait loop to watch for changes in a Bootstrap directory:

while inotifywait -r -q --format %w bootstrap/; do
    echo "something happened"
    [[ $filename == *.js ]] && uglifyjs .....
    [[ $filename == *.less ]] && lessc bootstrap.less
done

You don't really need to worry about the internals but I just can't get the filename back into a bash scope. inotifywait echos out the filename (with help from the format argument) but how do I capture that and use it later on (in my case, as $filename)?


If you want a simple, short test harness:

touch testfile
while inotifywait testfile do; echo "..."; done

And then you can just run touch testfile when you want to trigger it.

1
  • Stopping by in 2016, but the answer seems to be --format "%w%f", since %w` yields the directory of the file and %f the base filename. Not sure how this handles symlinks or the like.
    – Pockets
    Jul 19, 2016 at 19:49

2 Answers 2

22

The cleaner way is illustrated in this blog entry:

inotifywait -m -r -q --format '%w' bootstrap/ | while read FILE
do
  echo "something happened on path $FILE"
done
4
  • 7
    Format probably needs to be '%f' instead of '%w' to get filename May 24, 2016 at 11:50
  • 2
    And to get path+filename --format '%w%f', that is a usable path : ' )
    – edencorbin
    Jul 26, 2017 at 18:19
  • Can we prevent the double outputs?
    – daparic
    Nov 2, 2018 at 2:49
  • @eigenfield to prevent double outputs, add -e create or whatever event you want to filter on. I think duplicate outputs are happening because create/open/close events are happening all at once.
    – Clete2
    Apr 22, 2022 at 11:13
3

Turns out I just needed to restructure the while so that I captured the output of inotifywait:

while true; do
    echo "something happened"
    filename=$(inotifywait -r -q --format %w bootstrap/)
    [[ $filename == *.js ]] && uglifyjs .....
    [[ $filename == *.less ]] && lessc bootstrap.less
done

I'm still curious to know if there are cleaner ways of doing this.

1
  • 3
    The answer by @abergmeier is continuous so you won't miss events that occur while you are processing eg: uglifyjs or lessc etc.
    – bucabay
    Nov 23, 2014 at 15:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .