-3

I'm trying to write a bash script to monitor a directory for changes. If the file is a .go or .html file I would like to kill a specific process and then start it.

This is failing all over the place and I'm not sure why. I tried my best to get this working after scouring a lot of web sites for help but I can't get it.

The ideal solution is that I would run it by passing a directory and a file to run and it would just reload the process when I save a file.

I am running it like so:

./gowatcher /path/to/my/directory/to/watch foo.go

Here's what I have so far:

#!/usr/bin/env bash

WATCH_DIR=$1
FILENAME=$2

function restart_goserver() {
  if go run $FILENAME
  then
    pkill -9 -f $FILENAME > /dev/null 2>&1
    pkill -9 -f a.out > /dev/null 2>&1
    go run $FILENAME &
    echo "started $FILENAME"
  else
    echo "server restart failed"
  fi
}

cd $WATCH_DIR
restart_goserver

echo "watching directory: $WATCH_DIR"
inotifywait -mrq -e close_write $WATCH_DIR | while read file
do
  if grep -E '^(.*\.go)|(.*\.html)$'
  then
    echo "--------------------"
    restart_goserver
  fi
done
AntelopeSalad
  • 1,736
  • 1
  • 16
  • 27

1 Answers1

2

This line seems wrong :

grep -E '^(.*\.go)|(.*\.html)$'

Should be :

echo "$file" | grep -E '^(.*\.go)|(.*\.html)$'

Moreover, don't use kill -9 by default ! See In what order should I send signals to gracefully shutdown processes?

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223