Writing a Zsh function that auto reruns a command on file save

468 views Asked by At

I want to write a Zsh function that looks like:

smartwatch [WATCH_FILE] [COMMAND_TO_RUN] [COMMAND_ARGS]

Such that after WATCH_FILE is saved, that COMMAND_TO_RUN will be run and smartwatch will wait for the file to be saved again. This would be helpful for me in this scenario:

smartwatch server.py python server.py

So everytime I modify the server file, the server gets restarted. I've heard that inotify-tools might be able to help, so I'm using inotifywait, but if someone knows a better tool, let me know. Here's what I have so far:

smartwatch() {                      
   WATCH=$1                         
   CMD=$2                           
   ARGS=$*[3,-1]                    
   $CMD $ARGS &!                    
   PID=$!                           
   inotifywait -qq $WATCH           
   kill $PID                        
   exec smartwatch $WATCH $CMD $ARGS
}    

This solution is rather slow and not very elegant. Anyone know a way to make this more efficient or at least cleaner?

1

There are 1 answers

0
Corey Farwell On BEST ANSWER

After some fiddling, here's what I ended up with:

onsave() {
   while true
   do
      eval "$1 &!"
      trap "kill $! &> /dev/null; return;" SIGINT SIGTERM
      inotifywait -e modify -qq $2
      kill $! &> /dev/null
   done
}

So you should be able to run onsave "python server.py" server.py