Recompile and Test

When writing scripts or playing with new C++ language features I find it helpful if the code gets recompiled and executed as soon as I change a file in the source directory. I wrote a simple bash function that produces the desired effect and can be used independent of a certain language. The script requires inotifywait provided by inotify-tools (on Debian). Using the function is as easy as:

# usage: watchdir <dir to watch> '<shell command>'
watchdir src 'make_obi && ../build/run'
watchdir . ./some_bash_script

Below you will find the function’s implementation:

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
)}

Note: The sub-shell is required as the command’s execution could change the directory, but the command should still be called from the same$PWDin subsequent calls.

Leave a Reply

Your email address will not be published. Required fields are marked *