让Bash脚本一直运行但可中止

5

我有一个类似这样的bash脚本:

#!/bin/bash
startsomeservice &
echo $! > service.pid

while true; do
    # dosomething in repeat all the time here
    foo bar
    sleep 5
done

# cleanup stuff on abort here
rm tmpfiles
kill $(cat service.pid)

这个脚本的问题是,我无法中止它。如果我按下ctrl+c,我只会进入下一个循环... 是否有可能运行这样的脚本,但可以中止它?

4个回答

6

由于您正在使用Bash执行脚本,因此可以执行以下操作:

#!/bin/bash

startsomeservice &
echo $! > service.pid

finish()
{
    rm tmpfiles
    kill $(cat service.pid)
    exit
}
trap finish SIGINT

while :; do
    foo bar
    sleep 5
done

请注意,此行为仅适用于Bash,如果您在Dash中运行它,您将看到两个差异:
  1. 您无法捕获SIGINT
  2. 中断信号将打破shell循环。
请注意,即使您正在运行Bash,当您直接从交互式提示符执行循环时,单个C-c也会打破shell循环。有关来自shell的SIGINT处理的详细讨论,请参见此处的详细讨论

2
以下bash脚本将一直运行,直到它接收到一个终止信号。trap命令负责处理SIGINT信号。
#!/bin/bash

keepgoing=1
trap '{ echo "sigint"; keepgoing=0; }' SIGINT

while (( keepgoing )); do
    echo "sleeping"
    sleep 5
done

0

你也可以通过类似以下简单的方式完成任务:

#!/bin/bash

startsomeservice &

read # wait for user input

finish

0

我会使用:

tail -f /var/log/apache2/error.log & wait ${!}

在脚本的末尾,我认为sleep会导致延迟信号处理,但这行代码将立即响应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接