你如何确定一个新贵的工作是否在 Bash 脚本中运行?那就是我需要一个“布尔值”来做这样的事情:
#!/bin/bash
if [ determine_if_job_x_is_running ]; then
echo "I see upstart job X is running, please stop it before ..."
fi
Run Code Online (Sandbox Code Playgroud)
创建您自己的 Bash 函数并将其放入您的~/.bashrc:
check_upstart_service(){
status $1 | grep -q "^$1 start" > /dev/null
return $?
}
Run Code Online (Sandbox Code Playgroud)
我真的不喜欢解析输出的方式,但我没有看到另一种明显的方式。在这种情况下, 的输出<service name> start非常可靠,因为它在Upstart 文档中指定。
现在你可以像这样使用它:
if check_upstart_service ssh; then echo "running"; else echo "stopped"; fi
Run Code Online (Sandbox Code Playgroud)
通常您使用 PID 文件,但也可以使用 pgrep 来检查进程。假设您的服务被调用,jobX这将起作用:
if [ $(pgrep jobX) ]; then
Run Code Online (Sandbox Code Playgroud)
或者甚至更好
if pgrep jobX > /dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
您可以使用 DBUS 查询该特定服务的状态。
$ job=myjob
$ dbus-send --system --print-reply --dest=com.ubuntu.Upstart /com/ubuntu/Upstart/jobs/${job}/_ org.freedesktop.DBus.Properties.GetAll string:''
Run Code Online (Sandbox Code Playgroud)
http://upstart.ubuntu.com/cookbook/#get-status-of-job-via-d-bus
请注意,如果您正在编写自己的 upstart 作业,则应该使用 upstart 事件或包依赖项。