bash 检查进程是否正在运行,如果没有,使用 Cron 重新启动它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41023817/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:30:36  来源:igfitidea点击:

Check if a process is running and if not, restart it using Cron

bashshellunixawkcron

提问by iCyborg

I have created restart.sh with followin code

我已经使用以下代码创建了 restart.sh

#!/bin/bash
ps -aux | grep sidekiq > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

To check if sidekiq process is running or not. I will put this script in cron to run daily so if sidekiq is not running, it will start automatically.

检查 sidekiq 进程是否正在运行。我将把这个脚本放在 cron 中每天运行,所以如果 sidekiq 没有运行,它会自动启动。

My problem is, with

我的问题是,与

ps -aux | grep sidekiq

even when the process is not running, it shows

即使进程没有运行,它也会显示

myname 27906  0.0  0.0  10432   668 pts/0    S+   22:48   0:00 grep --color=auto sidekiq

instead of nothing. This gets counted in grep hence even when the process is not running, it shows as "sidekiq" process is running. How to not count this result ? I believe I have to use awk but I am not sure how to use it here for better filtering.

而不是什么都没有。这在 grep 中被计算在内,因此即使进程没有运行,它也会显示为“sidekiq”进程正在运行。这个结果怎么不计?我相信我必须使用 awk,但我不确定如何在这里使用它来更好地过滤。

回答by Inian

To exclude the grepresult from the psoutput. Do

grepps输出中排除结果。做

ps -aux | grep -v grep | grep sidekiq

(or) do a regExsearch of the process name, i.e. sfollowed by rest of the process name.

(或)regEx搜索进程名称,即s后跟进程名称的其余部分。

ps -aux | grep [s]idekiq

To avoid such conflicts in the search use process greppgrepdirectly with the process name

为了避免在搜索使用进程中greppgrep直接与进程名称发生这种冲突

pgrep sidekiq

An efficient way to use pgrepwould be something like below.

一种有效的使用方式pgrep如下所示。

if pgrep sidekiq >/dev/null
then
     echo "Process is running."
else
     echo "Process is not running."
fi