How to determine status of upstart job in bash script?
Solution 1:
Create your own Bash function and put this in your ~/.bashrc
:
check_upstart_service(){
status $1 | grep -q "^$1 start" > /dev/null
return $?
}
I really dislike the way of parsing output, but I don't see another obvious way. And in this case the output of <service name> start
is very reliable as it's specified in the Upstart documentation.
Now you can use it like this:
if check_upstart_service ssh; then echo "running"; else echo "stopped"; fi
Solution 2:
Normally you use a PID file but you can also use pgrep to check your processes. Assume your service is called jobX
this will work:
if [ $(pgrep jobX) ]; then
Or even better
if pgrep jobX > /dev/null 2>&1
Solution 3:
Based on String contains in bash:
job='your_job_name'
job_status=$(status ${job})
if [[ ${job_status} == *running* ]]
then
# do whatever you need
else
# do whatever you need
fi
My first impulse was to use variation of code ImaginaryRobots provided
job='your_job_name'
dbus-send --system --print-reply --dest=com.ubuntu.Upstart \
/com/ubuntu/Upstart/jobs/${job}/_ \
org.freedesktop.DBus.Properties.Get string:'' string:state
which would return something like
method return sender=:1.0 -> dest=:1.94 reply_serial=2 variant string "running"
and use the solution above to check if the returned string contains "running". However case that job is not running dbus call will exit with status 1 instead returning "waiting" as I was expecting.
status ${job}
would never exit with status 1 except in the case when there is no such job.