I have a script that I mean to be run from cron that ensures that a daemon that I wrote is working. The contents of the script file are similar to the following:
daemon_pid=`ps -A | grep -c fsdaemon`
echo "daemon_pid: " $daemon_pid
if [ $daemon_pid -eq 0 ]; then
echo "restarting fsdaemon"
/etc/init.d/fsdaemon start
fi
When I execute this script from the command prompt, the line that echoes the value of $daemon_pid is reporting a value of 2. This value is two regardless of whether my daemon is running or not. If, however, I execute the command with back quotes and then examine the $daemon_pid variable, the value of $daemon_pid is now one. I have also tried single stepping through the script using bashdb and, when I examine the variables using that tool, they are what they should be.
My question therefore is: why is there a difference in the behaviour between when the script is executed by the shell versus when the commands in the script are executed manually? I’m sure that there is something very fundamental that I am missing.
You’re very likely encountering the
grepas part of the ‘answer’ fromps.To help fully understand what is happening, turn off the
-coption, to see what data is being returned from justps -A | grep fsdameon.To solve the issue, some systems have a p(rocess)grep (
pgrep). That will work, ORIs a common idiom you will see, but at the expense of another process.
The cleanest solution is,
The regular expression syntax should work with all greps, on all systems.
I hope this helps.