Automatically update and upgrade Raspbian
Continuing the theme of last night, today I improved the upgrade experience of my Raspberry Pi.
As per the documentation, update and upgrade are as easy as running these two commands. First
update your system’s package list:
sudo apt -y update
upgrade all installed packages to their latest version:
sudo apt -y dist-upgrade
-y to answer yes to all prompts by default. Easy enough, but in our modern DevOpsy world, we need to automate this.
Automation to the rescue
I created a simple script in
bash which creates these two commands as scheduled tasks using
Cron. The image below shows my output of
Let’s go through the update command from the script as an educational example :
if crontab -l | grep -q "sudo apt -y update"; then echo "Auto update of package list already exists in crontab" else echo "Adding auto update of package list to crontab" (crontab -l 2>/dev/null; echo "0 3 * * * sudo apt -y update"); echo | crontab - fi
- First we check if this command already exist in
crontab. This StackOverflow answer helped me here.
- If it does, our work is already done. Idempotent scripts are something to strive for, and this achieves it. We can run this script again and again with the same result.
- If crontab lacks our entry, we add it. The first
2>/dev/nullis there so that we don’t get the
no crontab for usernamemessage if there are currently no crontab entries. Then we create our entry making the
updatecommand run every night at 03:00. Lastly, we pipet this to
crontabusing standard out.
- I did the same for the
upgradecommand, just made it run an hour later so that
updatealways completes first. To understand the cron patterns for when the task should run, see my post from yesterday.
Thus this script can be run anytime and the end result is that crontab runs both of these commands nightly.
The script can be downloaded and run directly on your Raspberry Pi, remember
chmod +x, or it can be run straight from GitHub using
curl -s https://raw.githubusercontent.com/Sankra/dotfiles/master/tasks/auto-update | sudo sh
Remember to never run scripts from the Internet without first understanding them!
The entire script looks like this:
#!/bin/bash set -e echo "Installing automatic updates..." if crontab -l | grep -q "sudo apt -y update"; then echo "Auto update of package list already exists in crontab" else echo "Adding auto update of package list to crontab" (crontab -l || true; echo "0 3 * * * sudo apt -y update") | crontab - fi if crontab -l | grep -q "sudo apt -y dist-upgrade"; then echo "Upgrade of installed packages already exists in crontab" else echo "Adding upgrade of installed packages" (crontab -l || true; echo "0 4 * * * sudo apt -y upgrade") | crontab - fi echo "Installation complete. Enjoy!"