Small script to watch and re-launch rust code

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.

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"
    echo "killing $PID"
    kill $PID
    unset PID
  cargo build
  if [ $? -eq 0 ]; then
    $1 &
    echo "Subshell started at $PID"

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.

Look at!

Oh nice.

Thanks =)

But cargo watch run is not always possible:

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

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.

1 Like