Reputation: 195
What I'm trying to do is to start a process if not started. Here is what I try
#!/bin/bash
pid=`ps ax | grep app | grep -v grep | wc -l`
if [ $pid = 0 ]
then
/etc/init.d/app start
fi
The problem is that the line
/etc/init.d/app start
is not executed. What is wrong here ? I know that I can you daemontools but I like the "bash" approach.
Upvotes: 0
Views: 3369
Reputation: 12946
I can't check on my servers right now, but Debian use start-stop-daemon to load services, it seems the right tool to use for your task, since it keeps track of your background process by PID and not just matching a name in the process list (which can do too).
Upvotes: 0
Reputation: 26086
If you have GNU ps
this is easy and doesn't require any craziness.
if ! ps -C app >/dev/null ; then
/etc/init.d/app start
fi
You just need to be careful that the app
you pass to ps
is the actual process name.
Upvotes: 0
Reputation: 46826
You can avoid the double grep by turning your keyword into a regex that doesn't match itself. And you can use grep -c
instead of counting with wc
. In your script, you could try:
pcount=`ps ax | grep -c "[a]pp"`
Alternately, use the actual pid instead of the process count:
#!/bin/bash
pid=`ps ax | awk '/[a]pp/{print $1}'`
if ! ps "$pid" >/dev/null; then
/etc/init.d/app start
fi
Note that this is still a very bad way to handle restarts of a service. You should see if app maintains its own pid file, perhaps somewhere in /var/run/, then test the contents of that.
#!/bin/sh
if [ -f /var/run/app.pid ]; then
if ps `cat /var/run/app.pid` >/dev/null; then
/etc/init.d/app start
fi
else
/etc/init.d/app start
fi
Or even better, launch app using daemontools runit or upstart or something equivalent that will take care of these things for you.
Upvotes: 2
Reputation: 65264
Take a look at the ==
operator.
Best may be something like
pid=`ps ax | grep app | grep -v grep`
test -z "$pid" && /etc/init.d/app start
Upvotes: 3