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 ?
sudo
in cronjobs - think: how do I enter password to sudo ? – Soren A Nov 11 '19 at 11:32sudo
without specifying a user in a script if root runs it in the first place (as it isroot
's crontab). – FelixJN Nov 11 '19 at 11:57