linux - 如何正确停止shell脚本?

标签 linux bash shell debian

我编写了一个小的 bash 脚本来每 3 秒启动一个程序。该脚本在启动时执行,并将其 PID 保存到 pid 文件中:

#!/bin/bash

echo $$ > /var/run/start_gps-read.pid

while [ true ] ; do
    if [ "$1" == "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

问题是,我无法通过调用 start_gps-read.sh stop 来终止 shell 脚本。它应该在那里读取 pid 文件并停止初始进程(从启动开始)。

但是当我调用 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

注意:脚本始终作为 sudo 执行。

有人知道如何停止我的 shell 脚本吗?

最佳答案

“停止”检查需要在覆盖 pid 文件之前进行,当然不需要在循环内。

if [ "$1" = 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

关于linux - 如何正确停止shell脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45102101/

相关文章:

php - 从 CronJob 启动时,Unix .sh 文件工作不正确

linux - tar bash 文件中名为 X 的每个子文件夹

ruby - RVM 警告! PATH 设置不正确

linux - 对文本文件中的每一行进行排序

php - 如何退出php shell命令

string - 在 Bash 中从末尾提取子字符串

ruby - Linux 使用重定向运行子进程而不产生新进程

linux - 如何在目录内容更改时自动调用 bash 脚本

bash - BASH中 "${1#*-}"是什么意思

linux - 不使用 ls 在 shell 中递归目录列表