Small script to watch and re-launch rust code


#1

Hi all

Today during development I had the need for a small script that would compile and relaunch my service so I came up with this small bash snippet. If there are better solutions out there I would love to be informed about them as I did not manage to find anything when looking around.

#!/bin/bash
inotifywait --monitor --event close_write,moved_to,create src |
while read -r directory events filename; do
  if [ -z "$PID" ]; then
    echo "$PID was not set"
  else
    echo "killing $PID"
    kill $PID
    unset PID
  fi
  cargo build
  if [ $? -eq 0 ]; then
    $1 &
    PID=$!
    echo "Subshell started at $PID"
  fi
done

Usage: script target/debug/binary

I gave it a small go and it seems to be able to handle error cases (currently it kills the old running program but launches a new one when compilation passes).

Having this functinality as part of cargo would be awesome, something like cargo run --watch or similar.


#2

Look at https://github.com/passcod/cargo-watch!


#3

Oh nice.

Thanks =)


#4

But cargo watch run is not always possible: https://github.com/passcod/cargo-watch/issues/25

So thx for the script! It can still make sense in some areas.


#5

Interesting, that’s exactly the use case I have that made me write it (A websocket server that needs to be restarted). I ran into the same issue that they did which is the reason you need to pass the compiled binary into the script as it will start and kill that process instead of killing the cargo run process.