If want to check if a process is running and start it if not. My script below is buggy and always says that a process is running. What is wrong?
$ ./check_n_run thisisnotrunning
./check_n_run: thisisnotrunning is already running
Here is the script:
$ cat check_n_run
#!/bin/sh
USAGE="usage: $0 processname"
if [ $# -ne 1 ] ; then
echo "$USAGE" >&2
exit 1
fi
ps ax | grep -v grep | grep $1> /dev/null
if [ $? -eq 1 ]
then
echo "$1 not running"
# start here
else
echo "$0: $1 is already running" >&2
fi
exit 0
ps|grepto excludegrepproperly from the results thegrep -vshould be after thegrep $1. However, the answers below are what you really need. (Even though I get 0 and 1 where you'd expect in tests in Bash on my system. But your test should be[ $? -ne 0 ].) – Dennis Williamson Jul 18 '10 at 23:37