You’ve come to the right place if you want to learn how to run Linux commands when any file in a working directory change and when new files are created.

In Linux, you may use cron to schedule commands to run at certain times.

But what if you need commands to be run every time a file is modified, or a new file is added to a directory?

That’s also easily achievable, and there are some command-line tools to perform that.

Let’s get started!

watchexec

watchexec is a handy and standalone tool that monitors a given working directory and executes a command if it detects any changes like file updation or new file creation.

Features

  • It does not require a complex command line involving xargs (extended arguments).
  • Checks for changes in the current directory and all subdirectories in real-time.
  • There is no need for a language runtime, and it is not connected to any specific language or ecosystem.
  • .gitignore and .ignore are used by default to decide which files to ignore notifications for.
  • Process groups are used to keep track of forking programs.
  • Watching files with a certain extension is supported.
  • It’s compatible with OS X, Linux, and Windows.
  • Filtering and ignoring events based on glob (File-search patterns for finding partially identical filenames is possible.

Installation of watchexec

To easily install watchexec tool, paste the following link into the terminal or a shell prompt, and press enter.

Linux & macOS

curl -sS https://webinstall.dev/watchexec | bash

After the successful installation, the path will be displayed on the screen. In my case, this tool was installed in /root/.local/bin

┌──(root💀kali)-[~]
└─# curl -sS https://webinstall.dev/watchexec | bash

Thanks for using webi to install '[email protected]' on 'Linux/x86_64'.
Have a problem? Experience a bug? Please let us know:
        https://github.com/webinstall/webi-installers/issues

Lovin' it? Say thanks with a Star on GitHub:
        https://github.com/webinstall/webi-installers

Found /root/Downloads/webi/watchexec/cli-v1.18.9/watchexec-1.18.9-x86_64-unknown-linux-musl.tar.xz
Extracting /root/Downloads/webi/watchexec/cli-v1.18.9/watchexec-1.18.9-x86_64-unknown-linux-musl.tar.xz
Installing to /root/.local/opt/watchexec-vcli-v1.18.9/bin/watchexec
Installed 'watchexec vcli-v1.18.9' as /root/.local/bin/watchexec

And after installation, navigate to the .local/bin repository and check whether the file is there or not by using these commands.

cd .local/bin

ls

The next step is to export the path to use the watchexec tool.

export PATH="https://geekflare.com/root/.local/bin:$PATH"

To run, Just type watchexec in the terminal as a root user. Use this command to see which flags and options can be used with watchexec tool.

watchexec --help

Sample Example Commands

  • Call ls -la when any file changes in this directory/subdirectory. This command shows all the files present in the directory whenever it detects any modification.
watchexec -- ls -la
  • Whenever any of the python, js, CSS, or Html extension files in the current directory change, run the command. Here you can pass any command you want. The file extensions should be separated by a comma.
 watchexec --exts py,js,css,html 
  • Run command when any file in lib or src changes. “-w” option watches a specific file or directory in the system.
watchexec -w lib -w src 
  • Call/restart any service when any file in the current directory (and all subdirectories) changes.
watchexec -e html -r tor

watchexec -e js,py -r mysql

Here, “-r” option restarts the process or service if it’s running in the system.

For more watchexec usage examples, you can visit the official GitHub repository.

entr

entr is a simple and excellent command-line utility for running arbitrary commands when any modifications occur in a given directory.

entr” stands for Event Notify Test Runner. This tool was created with the goal of making rapid feedback and automated testing.

Installation

entr is pre-installed in the Linux distribution. In case it’s missing, you need to install it manually.

This tool is simple to use and can be installed with the following command.

sudo apt-get install entr

Or you can also install it by cloning the official Git repository.

git clone https://github.com/eradman/entr.git

Next, navigate to that directory and install the requirements using the below commands.

./configure
make test
make install

To see available build options run ./configure -h

Sample Example Commands

To see the options and arguments available for entr command. Use the following command.

man entr

This command displays the user manual for the entr command.

NAME
     entr — run arbitrary commands when files change

SYNOPSIS
     entr [-acdnprsz] utility [argument /_ ...]

DESCRIPTION
     A list of files provided on standard input, and the utility is executed using the supplied arguments
     if any of them change.  entr waits for the child process to finish before responding to subsequent
     file system events.  A TTY is also opened before entering the watch loop in order to support interac‐
     tive utilities.

     The arguments are as follows:

     -a      Respond to all events which occur while the utility is running.  Without this option, entr
             consolidates events in order to avoid looping.  This option has no effect in conjunction with
             the -r flag.

     -c      Clear the screen before invoking the utility specified on the command line.  Specify twice to
             erase the scroll back buffer.

     -d      Track the directories of regular files provided as input and exit if a new file is added.
             This option also enables directories to be specified explicitly.  If specified twice, all new
             entries to a directory are recognized, otherwise files with names beginning with ‘.’ are ig‐
             nored.

     -n      Run in non-interactive mode.  In this mode entr does not attempt to read from the TTY or
             change its properties.

     -p      Postpone the first execution of the utility until a file is modified.

 Manual page entr(1) line 1 (press h for help or q to quit)
  • To launch and auto-reload a MySQL server when any JavaScript file changes in the working directory. Each time the changes are saved to the file, entr reloads the MySQL server.
 ls *.js | entr -r mysql
  • To Auto-reload a web server or terminate if the server exits.
$ ls * | entr -rz ./httpd

For more details and examples on entr command, you can visit their official GitHub repository.

Final Words 👩‍💻

I hope you found this article very useful in learning how to run Linux commands when any file in a given directory changes and when new files are created.

You may also be interested in learning how to remove files and directories in Linux.