如果尚未运行则运行脚本 - 获取[0:未找到

时间:2015-04-30 05:15:36

标签: linux bash shell if-statement ubuntu-14.04

如果尚未使用其他脚本运行,我尝试运行脚本。

test $ ls
arcane_script.py  calling_script.sh

这就是我的剧本现在所看到的

test $ cat calling_script.sh 
#!/bin/bash

PROCESSES_RUNNING=$(ps -ef | grep "arcane_script.py" | grep -v "grep" | wc -l)
echo $PROCESSES_RUNNING
if [$PROCESSES_RUNNING = "0"]; then
    /usr/bin/python arcane_script.py
fi;

我已尝试if块中的其他变体,例如[$PROCESSES_RUNNING -eq 0],但所有变体都输出相同的错误消息

test $ ./calling_script.sh 
0
./calling_script.sh: line 5: [0: command not found
test $ sh calling_script.sh 
0
calling_script.sh: 5: calling_script.sh: [0: not found

我做错了什么,如何解决?我已经用Google搜索了,但找不到多少帮助。

3 个答案:

答案 0 :(得分:2)

括号周围需要一个空格:

[ $PROCESSES_RUNNING = "0" ]

原因是[实际上是命令的名称,而在shell中,所有命令必须用空格与其他单词分开。

答案 1 :(得分:2)

在bash中,您需要用空格保护括号。括号只是test命令的简写。并且在bash命令中必须用空格分隔。有关详细信息,请参阅this link。因此,您需要编写if [ condition ]而不是if [condition]

答案 2 :(得分:1)

更坚实的方法是使用pid文件。然后,如果pid文件存在,您就知道它是一个正在运行的进程。 我们的想法是在程序开始时将processID写入文件(例如在/ tmp中),并在结束时将其删除。另一个程序可以简单地检查pid文件是否存在。

在python文件的开头添加类似

的内容
#/usr/bin/env python

import os
import sys

pid = str(os.getpid())
pidfile = "/tmp/arcane_script.pid"

if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
else:
    file(pidfile, 'w').write(pid)

# Do some actual work here


#
os.unlink(pidfile)

这样你甚至不需要额外的bash启动脚本。 如果你想使用bash检查,只需查看pid:

cat /tmp/arcane_script.pid 2>/dev/null && echo "" || echo "Not running"

请注意,如果脚本未正确结束,则需要手动删除pid文件。

PS。如果要自动检查PID是否存在,请查看Monit。如果需要,它可以重新启动程序。

相关问题