In an earlier installment of Linux Fu, I mentioned how you can use inotifywait to efficiently watch for file system changes. The comments had a lot of alternative ways to do the same job, which is great. But there was one very easy-to-use tool that didn’t show up, so I wanted to talk about it. That tool is entr. It isn’t as versatile, but it is easy to use and covers a lot of common use cases where you want some action to occur when a file changes.

The program is dead simple. It reads a list of file names on its standard input. It will then run a command and repeat it any time the input files change. There are a handful of options we’ll talk about in a bit, but it is really that simple. For example, try this after you install entr with your package manager.

  1. Open two shell windows
  2. In one window, open your favorite editor to create an empty file named /tmp/foo and save it
  3. In the second window issue the command: echo "/tmp/foo" | entr wc /tmp/foo
  4. Back in the first window (or your GUI editor) make some changes to the file and save it while observing the second window

If you can’t find entr, you can download it from the website.

Frequently, you’ll feed the output from find or a similar command to entr.

What It Isn’t

I had mentioned incron before as a way to attach actions to file changes. It also makes things easier, although perhaps not as easy as entr. As the name suggests, incron does for filesystem changes what cron does for time. That is, it causes some action to occur any time the specified file system changes happen. That survives a reboot or anything else short of you canceling it. This is very different from entr. With entr, the command runs like a normal application. As long as it is running, changes in the target files will trigger the specified action. When you stop the program, that’s the end of it. Usually, you’ll stop with a Control+C or a “q” character.

Speaking of the keyboard, you can also press space to trigger the action manually, as though a file changed. So, unlike incron, entr is an interactive tool. You’ll want it running in the foreground.

Options

There are several command line options:

  • -c – Clear screen before executing command
  • -d – Track directories that do not start with “.”
  • -p – Do not execute the command until an event occurs
  • -r – Kill previously run command before executing command
  • -s – Use shell on first argument

The /_ placeholder gets the name of the first file that caused a trigger, although that doesn’t seem to work properly with -s. For example:

find /tmp/t/data -name '*.txt' | entr cp /_ /tmp/archive

When one of the .txt files changes, it will copy to /tmp/archive.

The -d option has a peculiarity. With it you can use a directory name or a file name and the program will watch that directory along with any files. The file changes behave as …read more

Source:: Hackaday