检查程序是否正在使用 bash shell 脚本运行?
这是 bash 脚本的示例,它检查某些正在运行的进程(守护程序或服务),并在没有此类进程运行时执行特定操作(重新加载、发送邮件)。
check_process(){
# check the args
if [ "$1" = "" ];
then
return 0
fi
#PROCESS_NUM => get the process number regarding the given thread name
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
# for degbuging...
$PROCESS_NUM
if [ $PROCESS_NUM -eq 1 ];
then
return 1
else
return 0
fi
}
# Check whether the instance of thread exists:
while [ 1 ] ; do
echo 'begin checking...'
check_process "python test_demo.py" # the thread name
CHECK_RET = $?
if [ $CHECK_RET -eq 0 ]; # none exist
then
# do something...
fi
sleep 60
done
然而,这不起作用。我收到“错误:垃圾选项”。对于 ps
命令。这些脚本有什么问题?谢谢!
This is an example of a bash script which checks for some running process (daemon or service) and does specific actions (reload, sends mail) if there is no such process running.
check_process(){
# check the args
if [ "$1" = "" ];
then
return 0
fi
#PROCESS_NUM => get the process number regarding the given thread name
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
# for degbuging...
$PROCESS_NUM
if [ $PROCESS_NUM -eq 1 ];
then
return 1
else
return 0
fi
}
# Check whether the instance of thread exists:
while [ 1 ] ; do
echo 'begin checking...'
check_process "python test_demo.py" # the thread name
CHECK_RET = $?
if [ $CHECK_RET -eq 0 ]; # none exist
then
# do something...
fi
sleep 60
done
However, it doesn't work. I got "ERROR: Garbage option." for the ps
command. What's wrong with these scripts? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过这句话实现
PROCESS_NUM
中的几乎所有内容:如果您正在寻找部分匹配,即程序名为 foobar 并且如果您希望您的
$1
只是 foo 您可以将-f 开关
添加到 pgrep:将它们放在一起,您的脚本可以像这样重新编写:
运行它看起来像这样:
希望这样有帮助!
You can achieve almost everything in
PROCESS_NUM
with this one-liner:if you're looking for a partial match, i.e. program is named foobar and you want your
$1
to be just foo you can add the-f switch
to pgrep:Putting it all together your script could be reworked like this:
Running it would look like this:
Hope this helps!
如果您想执行该命令,您可能应该将:更改
为:
If you want to execute that command, you should probably change:
to: