使用inotifywait遇到了问题,尝试监视一个目录以便检测golang的变化。

huangapple go评论87阅读模式
英文:

Having trouble with inotifywait, trying to watch a directory for golang changes

问题

我正在尝试编写一个bash脚本来监视一个目录的变化。如果文件是.go或.html文件,我想要杀死一个特定的进程然后重新启动它。

这个脚本在很多地方都失败了,我不确定为什么。我尽力在浏览了很多网站寻求帮助后让它工作,但是我无法做到。

理想的解决方案是,我通过传递一个目录和一个要运行的文件来运行它,当我保存一个文件时它会重新加载进程。

我像这样运行它:

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

以下是我目前的代码:

#!/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
英文:

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

答案1

得分: 2

这一行似乎有问题:

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

应该是:

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

此外,默认情况下**不要使用kill -9!**请参考https://stackoverflow.com/questions/690415/in-what-order-should-i-send-signals-to-gracefully-shutdown-processes

英文:

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 https://stackoverflow.com/questions/690415/in-what-order-should-i-send-signals-to-gracefully-shutdown-processes

huangapple
  • 本文由 发表于 2012年12月3日 02:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/13672551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定