运行 如果还没有脚本 运行 - 得到 [0: 未找到
Run a script if not already running - getting [0: not found
我正在尝试 运行 一个脚本,如果尚未 运行 使用另一个脚本。
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
我做错了什么,我该如何解决?我四处搜索,但找不到太多帮助。
您需要在方括号中加上 space:
[ $PROCESSES_RUNNING = "0" ]
原因是 [
实际上是命令的名称,在 shell 中所有命令必须与其他单词分开 spaces。
在 bash 中,您需要用空格保护括号。括号只是 test
命令的 shorthand。而在 bash 中命令必须用空格分隔。有关详细信息,请参阅 this link。所以你需要写 if [ condition ]
而不是 if [condition]
.
更可靠的方法是使用 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。如果需要,它可以重新启动程序。
我正在尝试 运行 一个脚本,如果尚未 运行 使用另一个脚本。
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
我做错了什么,我该如何解决?我四处搜索,但找不到太多帮助。
您需要在方括号中加上 space:
[ $PROCESSES_RUNNING = "0" ]
原因是 [
实际上是命令的名称,在 shell 中所有命令必须与其他单词分开 spaces。
在 bash 中,您需要用空格保护括号。括号只是 test
命令的 shorthand。而在 bash 中命令必须用空格分隔。有关详细信息,请参阅 this link。所以你需要写 if [ condition ]
而不是 if [condition]
.
更可靠的方法是使用 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。如果需要,它可以重新启动程序。