英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论