Billy Moon
Billy Moon

Reputation: 58571

linux (and OSX) shell command to execute every time file is saved

I am trying to get jsdoc to automatically generate when I save my javascript file. I have got a working script that stores the last update time of a file (currently hardcoded) and compares with the current timestamp of that file. I run this in a while loop that runs until CTRL-C is pressed, and insert a 0.1 second sleep to stop the processor being consumed.

This is the working script:

while :
do

if [ $(( lastTime )) -ne `stat -f %m -t %s javascript.js` ]
then
        lastTime=`stat -f %m -t %s javascript.js`
        # custom jsdoc generating script
        jsdoc javascript.js
        echo +++ Run: `date`  +++
fi

# stops while loop from consuming a lot of resources
# and making my fan whirr like he wants the computer to take off
sleep .1

done

I know there is a better way - just not what that way is. Any help appreciated.

Edit: Update for linux machines with inotify-tools installed this should work

#!/bin/bash

# with inotify-tools installed...

# only watches first parameter for modification
while inotifywait -e modify $1; do
        echo
        echo +++ Building JSDocs +++
        jsdoc $@
        echo +++ Last run: `date`  +++
done

However, I would like this to work on both Linux and OSX shell, so I can use in both environments

Upvotes: 1

Views: 542

Answers (1)

Anders Abel
Anders Abel

Reputation: 69270

There is a linux kernel feature called INotify that watches the file system for any changes. It is exposed as a number of system APIs.

For scripting, there is a package called inotify-tools that gives scripting access to the notification system.

Upvotes: 3

Related Questions