bash 如何正确停止shell脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45102101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop a shell script correctly?
提问by Michael Gierer
I've written a small bash script to start a program every 3 seconds. This script is executed on startup and it saves its PID into a pidfile:
我写了一个小的 bash 脚本来每 3 秒启动一个程序。此脚本在启动时执行,并将其 PID 保存到 pidfile 中:
#!/bin/bash
echo $$ > /var/run/start_gps-read.pid
while [ true ] ; do
if [ "" == "stop" ] ;
then
echo "Stopping GPS read script ..."
sudo pkill -F /var/run/start_gps-read.pid
exit
fi
sudo /home/dh/gps_read.exe /dev/ttyACM0 /home/dh/gps_files/gpsMaus_1.xml
sleep 3
done
The problem is, I can't terminate the shell script by calling start_gps-read.sh stop
. There it should read the pidfile and stop the inital process (from startup).
问题是,我无法通过调用start_gps-read.sh stop
. 在那里它应该读取 pidfile 并停止初始进程(从启动)。
But when I call stop
, the script still runs:
但是当我调用时stop
,脚本仍然运行:
dh@Raspi_DataHarvest:~$ sudo /etc/init.d/start_gps-read.sh stop
Stopping GPS read script ...
dh@Raspi_DataHarvest:~$ ps aux | grep start
root 488 0.0 0.3 5080 2892 ? Ss 13:30 0:00 /bin/bash /etc/init.d/start_gps-read.sh start
dh 1125 0.0 0.2 4296 2016 pts/0 S+ 13:34 0:00 grep start
Note: The script is always executed as sudo
.
注意:脚本始终作为sudo
.
Does anyone know how to stop my shell script?
有谁知道如何停止我的 shell 脚本?
回答by chepner
The "stop" check needs to come before you overwrite the pid file, and certainly doesn't need to be inside the loop.
“停止”检查需要在覆盖 pid 文件之前进行,当然不需要在循环内。
if [ "" = stop ]; then
echo "Stopping ..."
sudo pkill -F /var/run/start_gps-read.pid
exit
fi
echo "$$" > /var/run/start_gps-read.pid
while true; do
sudo /home/dh/gps_read.exe ...
sleep 3
done