DEV Community

Cover image for Poor man's file watcher

Posted on

Poor man's file watcher

Image source

Suppose you want to perform a certain action each time one or more files change, for example running a spec each time they're updated.

You should definitely use something more polished like Guard but you could also experiment with a "simpler" approach.

First of all create the Ruby script check_event.rb:

# frozen_string_literal: true

last_mod =
loop do
  path_parts = gets.split
  path = "#{path_parts[0]}#{path_parts[2]}"
  next unless path.include?('_spec.rb')

  now =
  # Debounce: skip if another event has been notified less than a second ago.
  next if now - last_mod < 1

  last_mod = now
  puts `rspec "#{path}"`
Enter fullscreen mode Exit fullscreen mode

Make sure the command inotifywait is installed:

sudo apt install inotify-tools
Enter fullscreen mode Exit fullscreen mode

And then you can combine inotifywait with our Ruby script:

inotifywait --monitor --event modify --recursive ./spec | ruby check_event.rb
Enter fullscreen mode Exit fullscreen mode

Note: I added a debounce in the Ruby script. This is because a modify event is called twice upon file save (tested with Vim on Ubuntu).

Top comments (0)