익명 18:14

Why isn’t my Cron command working, but it works in the shell?

Why isn’t my Cron command working, but it works in the shell?

I have an extremely simple cronjob that I set up to make sure a script keeps running, and email me if it goes down (low tech, I know, but it was intended as a quick fix)

Unfortunately, this cronjob isn't doing its job

Here is the relevant line from my crontab:

* * * * * pgrep -f app.py || echo "Your app is down" | mail -s "URGENT" [email protected]

When I run the command in shell, it works: I receive an email only if the app is down. As a minor side effect, when the app is running, it outputs the PID to the screen.

When I run the command via a cronjob, I never get any emails. Investigating (by setting up the MAILTO= parameter to see the cronjob output) I noticed that when the app is running, it outputs two PIDs, and when the app is not running it outputs one PID (never zero, so it never sends an email)

It's almost as if the cronjob is spinning up a process which is, in turn, being seen by itself -- much like how typing ps -ax | grep "anything" will always return:

12345 pts/2    S+     0:00 grep --color=auto anything

Does anyone know how to fix this cronjob?



Top Answer/Comment:

To anyone who stumbles upon this in the future, the solution was fairly simple:

When running

pgrep -f "anything"

in a cronjob, it will return a process for the bash shell spawned by cron.

Instead I had to use

ps -ax | grep "anything" | grep -v grep

to search for the running process and simultaneously remove any process which had "grep" in the name

상단 광고의 [X] 버튼을 누르면 내용이 보입니다