Search code examples
linuxapachecron

Cron script to restart apache server doesn't work


This is the first time I'm using cron. I want to restart the apacher in my server if the amount of available memory goes less than 500 mb. To do so I wrote the following script:

restart_if_memory_full.sh (in /var/www/myapp/)

#!/bin/bash

mem=$(free -m | awk '/Mem:/{print $4}')
(( mem <= 500 )) && (sudo service apache2 restart)

Then I did it executable by running (sudo chmod +x restart_if_memory_full.sh) and added the following line to the cron by (sudo crontab -e) (Note I did not use .sh extension as recommended)

* * * * * /var/www/myapp/restart_if_memory_full 

Now, I check the output by (grep CRON /var/log/syslog) and see this:

Nov 11 11:13:01 mardy2 CRON[31963]: (root) CMD (/var/www/myapp/restart_if_memory_full)
Nov 11 11:13:01 mardy2 CRON[31962]: (CRON) info (No MTA installed, discarding output)

However, when I check the memory usage by htop, it doesn't decrease and therefore I realized apache server was not restarted. So, how can I make this script runnable ?


Solution

  • You basically answered your question yourself:

    Note I did not use .sh extension as recommended

    This is not just an extension, it's part of the filename. So if your script was saved as /var/www/myapp/restart_if_memory_full.sh you can't just remove the suffix. Cron won't find that file and will not do anything. Cron even would want to inform you about it by e-mail, but there is no mailserver installed to send an alert:

    (CRON) info (No MTA installed, discarding output).

    So use the full path and name of the script:

    * * * * * /var/www/myapp/restart_if_memory_full.sh