A bash function for automatically recompiling and executing code when source files change, perfect for development workflows.

The Problem

During development, especially when exploring new programming language features or working on scripts, you often need to repeatedly recompile and test your code. Manual compilation becomes tedious and interrupts your flow.

The Solution

I created a bash function called watchdir that automatically recompiles and runs code when source files change. This requires inotifywait from the inotify-tools package.

Installation

First, install the required dependency:

# On Debian/Ubuntu
sudo apt-get install inotify-tools

The watchdir Function

watchdir () 
{( 
    if (( $# < 2 )); then
        echo "usage: watchdir <directory> '<shell; command>'";
        exit 1
    fi
    local dir="$1";
    shift;
    while inotifywait --exclude '/\..+' -e MODIFY -e CLOSE_WRITE -r "${dir}"; do
        echo "### inotifywait exec - start #######################";
        echo "command: $*";
        sleep 0.1;
        "$@";
        echo;
        echo "### inotifywait exec - end #########################";
    done
)}

How It Works

  1. Directory Monitoring: Uses inotifywait to watch a specified directory recursively
  2. Event Filtering: Monitors MODIFY and CLOSE_WRITE events while excluding hidden files
  3. Command Execution: Runs the provided shell command when changes are detected
  4. Sub-shell Isolation: Uses a sub-shell to maintain consistent working directory

Usage

Simple usage example:

watchdir src 'make_obi && ../build/run'

This command will:

  • Watch the src directory for changes
  • Run make_obi && ../build/run whenever files are modified
  • Provide clear output delimiting each execution

Key Features

  • Automatic recompilation: No manual intervention needed
  • Flexible commands: Any shell command can be executed
  • Clear output: Execution boundaries are clearly marked
  • Hidden file exclusion: Ignores temporary and hidden files
  • Recursive monitoring: Watches subdirectories automatically

This function is particularly useful for developers working on scripts, exploring new programming language features, or anyone who needs rapid iteration cycles during development.