Reputation: 387
My script doesnt function properly when I execute using just sh, it used to function fine before until today. Even in cronjob it used to execute without a problem.
/bin/sh process_check.sh
But it seems to execute fine when I execute using the following way
./process_check.sh
Script (checks if a process is running, executes the process if it's not running)
#/bin/sh
$service=xxx
if (( $(/bin/ps -ef | grep $service | wc -l) > 1 ))
then
true
else
echo "$service is not running!!!"
/usr/sbin/xxx
fi
Also, any ways to make this much more efficient? I have a compiled program that I am trying to ensure is always running.
Upvotes: 1
Views: 2038
Reputation: 113994
One problem is this line:
$service=xxx
This likely should be:
service=xxx
Also, the following is inherently unreliable:
(( $(/bin/ps -ef | grep $service | wc -l) > 1 ))
The number of processes found this way in a multitasking system depends on accidents of timing. A more reliable approach is to use pgrep
:
pgrep "$service"
This will list PIDs for $service
without the possibility of matching the grep
process.
Because pgrep
sets a useful return code all by itself, there is no need for math test. Thus, replace:
if (( $(/bin/ps -ef | grep $service | wc -l) > 1 ))
With:
if pgrep -q "$service"
where -q
tells pgrep
to just set the exit code without listing the PIDs to stdout.
If your pgrep
does not support the -q
option, then use:
if pgrep "$service" >/dev/null
Upvotes: 1
Reputation: 31
In the first line of the script, you used #/bin/sh instead of #!/bin/sh. When you use ./process_check.sh it uses /bin/bash instead of /bin/sh.
Upvotes: 2