DEV Community

Jan Mewes
Jan Mewes

Posted on • Updated on

Run a Bash command after file changes [Linux/macOS]

This blog post shows how to run a Bash command every time a file changes on a UNIX system. To achieve this goal, we can use the entr project. The snippets in this post have been tested on Ubuntu and macOS.

Setup

Ubuntu

On Ubuntu, entr can be installed with APT:

sudo apt-get update
sudo apt-get install entr
Enter fullscreen mode Exit fullscreen mode

See https://howtoinstall.co/en/entr for further details.

macOS

On macOS, entr can be installed with Homebrew:

brew install entr
Enter fullscreen mode Exit fullscreen mode

See https://formulae.brew.sh/formula/entr for further details.

Usage

To execute a Bash command every time a file changes, we first need to create a file, e.g. with the help of the touch program:

touch /tmp/example.txt
Enter fullscreen mode Exit fullscreen mode

Now we can pipe the name of the file into the entr program and declare a Bash command which should be executed every time the file changes:

echo "/tmp/example.txt" | entr bash -c "echo 'File changed.'"
Enter fullscreen mode Exit fullscreen mode

If you now open the file /tmp/example.txt in a text editor, you will see "File changed." printed to the terminal, every time you save the file.

For further information, refer to the homepage or the source code of the entr project:

Top comments (0)