Crontab Problem

There was a problem in one of my bash scripts. The script (master-universe) is the starter of another script. It should be run daily at midnight to check  if a child process, which is the manager of the another script, is still running. If the child process is somehow dead, it will (re) execute the child.

I tested the script with bash and /bin/sh, it seems to be  working just fine.

The function above is the source of the problem. When it execute using crontab, it refused go inside the for loop as if  the process master-universe does not exist (checked via ps aux from cli).

My first thought was /bin/sh can’t interpret the for syntax for whatever reasons. But thats not true because when run it from the console

everything seemed allright.

After spending more than 1 hour debugging and nearly thrashing my mouse to the 19”  lcd, I realized it! I added a line to the code, and it revealed everything.

kill_master() {
ps aux > /tmp/napeTakSama.txt
for pid in ps aux| grep -v grep |grep 'master-universe' |awk '{print $2}'; do
echo “Killing pid: ” $pid
kill -9 $pid
done
}

Result of /tmp/napeTakSama.txt

Can you see the problem?

Yup.. the result of ps aux above is somehow truncated to 81 characters for each line and therefore my grep cannot find the master-universe string.

The Solution?
Instead of ps aux I just used ‘ps ax’ and filtered the first column.

The above code worked as I expected.

This happen on FreeBSD 7.2. (I hate bsd!) I tried the original code on Linux (Ubuntu Karmic) and  guess what? The result is as expected from a well behaved innocent OS.

(Note to myself: Remember, always love Linux).

Leave a Reply

Your email address will not be published. Required fields are marked *