I'm running this simple script on my Raspberry Pi to auto update so I can forget about it. It also keeps a log that says whether the update was successful. The script is update.sh:
#!/bin/bash echo "Update starts on: $(date)" >> /home/pi/update.log if apt-get update && apt-get upgrade -y; then echo "update successful $(date)" >> /home/pi/update.log else echo "Couldn't update $(date)" >> /home/pi/update.log fi
I added this script to the root crontab by using
sudo crontab -e and the cronjob is set to run every day at 6AM
0 6 * * * /home/pi/update.sh
I know that it works to some extent because running
sudo ./update.sh in the shell manually runs the commands and leaves a "successful" entry in the log. On the other hand, when ran from the crontab, I always get the "couldn't update" entry. In case it matters, the "update.sh" script was created by the "pi" user and I never changed the permissions, except giving it execution permissions.
I read another question about the same problem and the guy solved it by putting a
sudo in front of the command. He admits it's weird because it's already being executed by root, but says it works. I tried adding the
sudo and verified it actually works now.
Does anyone know why this happens? Why does it need the
sudo if it's already root?