auto-update.sh patches an Ubuntu or Debian server every night. It installs every update, including kept back and phased packages, reboots if one is needed and carries on afterwards, and can post the result to Discord. You can read the whole script below before you run it.
What it does
Keeping servers patched is one of those jobs thatâs important, boring and easy to forget. This script does it for you on Ubuntu and Debian. It installs every available update, deals with the packages that get kept back or held back by Ubuntuâs phased rollouts, and makes sure the server ends up fully up to date. If a reboot is needed, it reboots and then carries on where it left off. Set it up once and your servers look after themselves.

Iâve run it on Ubuntu 20.04, 22.04, 24.04 and 26.04, and on Debian and Raspberry Pi OS.
Why not unattended-upgrades?
Ubuntu already ships with unattended-upgrades, so itâs a fair question. I wrote this because of three things it doesnât do the way I wanted:
- It only installs security updates by default. I want every update, not just the security ones, without hand-editing its config on every server.
- Kept back and phased packages get left behind. Packages that need new dependencies, or that Ubuntu is rolling out gradually, sit there as âkept backâ for days or weeks. This script installs them.
- Reboots. I wanted it to reboot when an update needs one, and then pick up exactly where it stopped, so a server never gets left half patched.
The script
This is the exact script I run on all my servers apart from the Proxmox host. Download it, or read it below first:
Download: auto-update.sh
The source and history are on GitHub: Ubuntu-Auto-Update.
Or straight onto your server:
curl -fsSLO https://jackwent.co.uk/downloads/autopatch/auto-update.sh
The script has a signature next to it, auto-update.sh.sig, made with my release key. To check youâve got the file I published before you run it as root:
curl -fsSLO https://jackwent.co.uk/downloads/autopatch/auto-update.sh.sig
echo 'jackwent namespaces="auto-update" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKsjQ+laaFJX+9wRKAB09FusulCbVmQ+qgSGmCYxOUm/' > allowed_signers
ssh-keygen -Y verify -f allowed_signers -I jackwent -n auto-update -s auto-update.sh.sig < auto-update.sh
It prints Good "auto-update" signature when the file matches.
#!/bin/bash
# Enhanced Ubuntu Auto Patch Script with Phased Updates Support
# Version of this script. It is inside the signed file, so someone checking the .sig by hand can also see
# whether they were given an old release.
SCRIPT_VERSION="2"
# Runs as root (root's crontab). apt is called directly rather than through sudo: an autoremove
# after a release upgrade can remove sudo, which would then make every apt step fail.
if [ "$(id -u)" -ne 0 ]; then
echo "auto-update.sh must run as root" >&2
exit 1
fi
# STATE_DIR keeps what the run needs across reboots: its progress, the failed-step count, and what was
# installed before the run. It is under /var/lib (root only), because /var/log can be written by other
# groups and root follows symlinks there.
STATE_DIR="/var/lib/update-script"
mkdir -p "$STATE_DIR"
# One run at a time: a manual run overlapping the cron or @reboot run would race on the state files.
exec 9>"$STATE_DIR/lock"
if ! flock -n 9; then
echo "another auto-update.sh run is in progress; exiting"
exit 0
fi
# Define a file to track progress
PROGRESS_FILE="$STATE_DIR/progress"
# Options for every apt call that changes packages:
# - wait up to 10 minutes for another apt or unattended-upgrades run instead of failing
# - keep existing config files when a package ships a new default, without prompting
APT_OPTS=(-o DPkg::Lock::Timeout=600 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
# Discord report at the end of each run that changed something or failed (quiet otherwise).
# The webhook is read from HOOK_FILE (root-only); without it, no report is sent.
HOOK_FILE="/etc/auto-update/discord-webhook"
BEFORE_FILE="$STATE_DIR/packages-before"
REBOOTS_FILE="$STATE_DIR/reboots"
FAILED_FILE="$STATE_DIR/failed-steps"
# Count failed apt steps, so a bad run says so instead of "completed successfully".
# The count is kept in a file because a run can reboot part way and carry on after.
ERRORS_FILE="$STATE_DIR/errors"
# Older versions kept these two files in /var/log. They are never read now (a file in a directory other
# groups can write is not trusted state), so just remove them.
rm -f /var/log/update-script-progress /var/log/update-script-errors
ERRORS=$(cat "$ERRORS_FILE" 2>/dev/null || echo 0)
[[ "$ERRORS" =~ ^[0-9]+$ ]] || ERRORS=0
apt_step() {
if ! DEBIAN_FRONTEND=noninteractive apt "${APT_OPTS[@]}" "$@"; then
echo "ERROR: apt $* failed"
mkdir -p "$STATE_DIR" && echo "apt $*" >> "$FAILED_FILE"
ERRORS=$((ERRORS + 1))
echo "$ERRORS" > "$ERRORS_FILE"
fi
}
# Ubuntu flags a needed reboot with /var/run/reboot-required. Debian doesn't, so there
# a newer installed kernel than the running one also counts. KERNEL_MARK remembers the
# kernel we last rebooted for, so a system that boots an older kernel can't reboot-loop.
KERNEL_MARK="/var/lib/update-script-kernel"
reboot_needed() {
[ -f /var/run/reboot-required ] && return 0
[ -e /usr/share/update-notifier/notify-reboot-required ] && return 1
local newest
newest=$(find /boot -maxdepth 1 -name "vmlinuz-*" 2>/dev/null | sed "s#^/boot/vmlinuz-##" | sort -V | tail -n 1)
if [ -n "$newest" ] && [ "$newest" != "$(uname -r)" ] && [ "$(cat "$KERNEL_MARK" 2>/dev/null)" != "$newest" ]; then
echo "$newest" > "$KERNEL_MARK"
return 0
fi
return 1
}
# Function to check if a reboot is required
check_reboot() {
if reboot_needed; then
echo "Reboot required. Rebooting now..."
mkdir -p "$STATE_DIR"
echo $(( $(cat "$REBOOTS_FILE" 2>/dev/null || echo 0) + 1 )) > "$REBOOTS_FILE"
echo "step1_reboot" > "$PROGRESS_FILE"
reboot
exit 0
fi
}
# Function to check the progress and continue where left off
check_progress() {
if [ -f "$PROGRESS_FILE" ]; then
PROGRESS=$(cat "$PROGRESS_FILE")
case $PROGRESS in
"step1_reboot")
echo "Continuing after first reboot..."
step2_install_updates
;;
"step2_updates")
echo "Continuing after updates..."
step3_install_kept_back
;;
"step3_kept_back")
echo "Continuing after installing kept-back packages..."
step4_install_phased_updates
;;
"step4_phased")
echo "Continuing after installing phased updates..."
check_reboot_after_updates
;;
*)
echo "Unknown progress state, starting from the beginning."
start_script
;;
esac
else
start_script
fi
}
# Function to start the script
start_script() {
# A fresh run: remember the installed versions so the report can list what changed.
mkdir -p "$STATE_DIR"
dpkg-query -W -f='${Package} ${Version}\n' > "$BEFORE_FILE" 2>/dev/null
echo 0 > "$REBOOTS_FILE"
rm -f "$FAILED_FILE"
check_reboot
step2_install_updates
}
# Function to perform updates
step2_install_updates() {
echo "Updating package lists..."
apt_step update
echo "Upgrading installed packages..."
# Set non-interactive frontend to avoid prompts
apt_step upgrade -y
echo "step2_updates" > "$PROGRESS_FILE"
step3_install_kept_back
}
# Function to install kept-back packages
step3_install_kept_back() {
echo "Installing kept-back packages..."
# Set non-interactive frontend to avoid prompts
apt_step dist-upgrade -y
echo "step3_kept_back" > "$PROGRESS_FILE"
step4_install_phased_updates
}
# Function to install phased updates
step4_install_phased_updates() {
echo "Checking for phased updates..."
# Check for packages that have been kept back due to phasing
KEPT_BACK=$(apt list --upgradable 2>/dev/null | grep -v "^WARNING" | grep -v "^Listing" | wc -l)
if [ "$KEPT_BACK" -gt 0 ]; then
echo "Found $KEPT_BACK packages that may be held back due to phasing."
echo "Attempting to install all available updates including phased ones..."
# Method 1: Use the correct apt option to bypass phasing
echo "Running apt upgrade with phased updates included..."
apt_step -o APT::Get::Always-Include-Phased-Updates=true upgrade -y
# Method 2: Alternative using dist-upgrade with phasing override
echo "Running dist-upgrade with phased updates included..."
apt_step -o APT::Get::Always-Include-Phased-Updates=true dist-upgrade -y
# Method 3: If the above don't work, try installing specific packages
echo "Checking for any remaining upgradable packages..."
REMAINING_PACKAGES=$(apt list --upgradable 2>/dev/null | grep -v "^WARNING" | grep -v "^Listing" | awk -F'/' '{print $1}')
if [ -n "$REMAINING_PACKAGES" ]; then
echo "Installing remaining packages individually..."
# apt install marks a package as manually installed; remember which were
# automatic so autoremove can still clean them up later.
AUTO_BEFORE=$(apt-mark showauto 2>/dev/null)
for package in $REMAINING_PACKAGES; do
echo "Installing $package..."
DEBIAN_FRONTEND=noninteractive apt "${APT_OPTS[@]}" -o APT::Get::Always-Include-Phased-Updates=true install -y "$package" 2>/dev/null || echo "Failed to install $package (held packages are skipped)"
done
for package in $REMAINING_PACKAGES; do
if grep -qxF "$package" <<< "$AUTO_BEFORE"; then
apt-mark auto "$package" > /dev/null 2>&1 || true
fi
done
fi
else
echo "No packages appear to be held back."
fi
echo "step4_phased" > "$PROGRESS_FILE"
check_reboot_after_updates
}
# Function to check if a reboot is required after updates
check_reboot_after_updates() {
check_reboot
cleanup
}
# Function to clean up unnecessary packages
cleanup() {
echo "Cleaning up unnecessary packages..."
apt_step autoremove -y
apt_step autoclean
# Final check for any remaining updates
echo "Performing final update check..."
apt_step update
REMAINING_UPDATES=$(apt list --upgradable 2>/dev/null | grep -v "^WARNING" | grep -v "^Listing" | wc -l)
if [ "$REMAINING_UPDATES" -gt 0 ]; then
echo "Note: $REMAINING_UPDATES updates may still be available (possibly still phased)."
echo "To see them, run: apt list --upgradable"
else
echo "System is fully up to date."
fi
rm -f "$ERRORS_FILE"
report "$REMAINING_UPDATES"
rm -f "$BEFORE_FILE" "$REBOOTS_FILE" "$FAILED_FILE"
if [ "$ERRORS" -gt 0 ]; then
echo "Script finished with $ERRORS failed apt step(s). Check the log above."
rm -f "$PROGRESS_FILE"
exit 1
fi
echo "Script completed successfully."
rm -f "$PROGRESS_FILE"
}
# JSON string body from stdin (quotes, backslashes, tabs, newlines).
json_text() {
sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/ /g' | awk '{printf "%s\\n", $0}'
}
# Post the run's result to Discord: what changed (old -> new), reboots, what's still pending,
# failed steps. Nothing is sent for a run that installed nothing and had no errors.
report() {
local remaining="$1" url changes removed reboots failed title colour summary body
url=$(cat "$HOOK_FILE" 2>/dev/null) || return 0
[ -n "$url" ] || return 0
if [ -f "$BEFORE_FILE" ]; then
changes=$(dpkg-query -W -f='${Package} ${Version}\n' 2>/dev/null | awk 'NR==FNR {old[$1]=$2; next}
!($1 in old) {print $1 " (new) " $2; next} old[$1] != $2 {print $1 " " old[$1] " -> " $2}' "$BEFORE_FILE" -)
removed=$(dpkg-query -W -f='${Package}\n' 2>/dev/null | awk 'NR==FNR {now[$1]=1; next} !($1 in now)' - "$BEFORE_FILE" | wc -l)
fi
reboots=$(cat "$REBOOTS_FILE" 2>/dev/null || echo 0)
failed=$(cat "$FAILED_FILE" 2>/dev/null)
if [ -z "$changes" ] && [ "$reboots" -eq 0 ] && [ "$ERRORS" -eq 0 ]; then
return 0
fi
local n=0
[ -n "$changes" ] && n=$(printf '%s\n' "$changes" | wc -l)
if [ "$ERRORS" -gt 0 ]; then
title="â $(hostname -s): patching had $ERRORS failed step(s)"; colour=15158332
elif [ "${remaining:-0}" -gt 0 ]; then
title="đ©č $(hostname -s) patched, $remaining still pending"; colour=16098851
else
title="đ©č $(hostname -s) patched"; colour=4437377
fi
summary="**$n package(s) updated**"
[ "${removed:-0}" -gt 0 ] && summary="$summary · $removed removed"
[ "$reboots" -gt 0 ] && summary="$summary · rebooted ${reboots}Ă"
summary="$summary · ${remaining:-0} pending"
body="$summary"
[ -n "$failed" ] && body="$body"$'\n'"Failed: "$'\n'"\`\`\`"$'\n'"$failed"$'\n'"\`\`\`"
if [ -n "$changes" ]; then
body="$body"$'\n'"\`\`\`"$'\n'"$(printf '%s\n' "$changes" | head -40)"
[ "$n" -gt 40 ] && body="$body"$'\n'"âŠand $((n - 40)) more"
body="$body"$'\n'"\`\`\`"
fi
printf '{"embeds":[{"title":"%s","description":"%s","color":%s,"footer":{"text":"auto-update.sh · %s"},"timestamp":"%s"}],"allowed_mentions":{"parse":[]}}' \
"$(printf '%s' "$title" | json_text | sed 's/\\n$//')" "$(printf '%s' "$body" | cut -c1-3800 | json_text)" "$colour" \
"$(uname -r)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
| curl -sS -m 15 -o /dev/null -H 'Content-Type: application/json' -d @- "$url" || echo "Discord report failed"
}
# Function to show current phasing status (optional utility)
show_phasing_info() {
echo "Current phasing information:"
echo "APT_CONFIG_PHASING: ${APT_CONFIG_PHASING:-not set}"
echo "Available phased updates:"
apt list --upgradable 2>/dev/null | grep -E "\[.*phased.*\]" || echo "None found"
}
# Uncomment the next line to see phasing info before starting
# show_phasing_info
# Start or continue the script
check_progress
How does it work?
- Checks for a pending reboot. If a previous change already needs a reboot, it reboots first, before touching anything.
- Updates and upgrades. It refreshes the package lists (
apt update) and upgrades everything installed (apt upgrade). - Installs kept back packages.
apt dist-upgradepulls in the updates that need new or removed dependencies, which a normal upgrade keeps back. - Installs phased updates. Ubuntu releases some updates to a few machines at a time, so they can stay held back even after step 3. The script tells apt to include them, then installs anything still outstanding one package at a time, so one awkward package canât stop the rest.
- Reboots if needed. If the updates need a reboot (a new kernel, for example), it reboots.
- Tidies up. It removes packages that are no longer needed, clears the cache, and logs whether anything is still outstanding.
- Reports to Discord. If youâve given it a Discord webhook, it posts one message when the run ends. The message lists each package it changed with the old and new version, how many times it rebooted, whatâs still pending and any step that failed. A run with nothing to install sends nothing.
It writes its progress to /var/lib/update-script/progress after each step. When it runs again after a reboot, it reads that file and continues from the next step. Once a full run finishes, it deletes the file so the next night starts fresh.
Where I use it
It patches every one of my servers at midnight, Proxmox VMs and Raspberry Pis alike. The only exception is the Proxmox host itself. They all start at the same time, so if several need a reboot they restart together just after midnight.
I keep an eye on it in three ways:
- A Home Assistant dashboard shows how many updates are outstanding on each server. The numbers come from my MQTT agent, so if a server hasnât patched, I can see it at a glance, and its Reboot Required sensor shows anything waiting on a restart.
- A Discord channel that each server posts its report to after it patches, so I can see what changed overnight without logging in to anything.
- A morning fleet check from Jarvis, my AI assistant, which reports on every server.
When it went wrong
It has bitten me once. A Docker update had a bug in it, and after the upgrade and the reboot that followed, Docker wouldnât start, so neither did any of the containers on that server. I knew straight away, because Home Assistant alerted me that the serverâs services were down, and a small change to Dockerâs daemon config got it running again.
It was a one-off, so Iâve left my setup as it is. If youâd rather not take that risk with something important, you can stop a package from being upgraded automatically (see the FAQ below), and take a snapshot or backup before patching anything other things depend on.
How do I set it up?
Save the script to your server:
sudo install -d -m 0755 /opt/scripts
sudo curl -fsSL -o /opt/scripts/auto-update.sh https://jackwent.co.uk/downloads/autopatch/auto-update.sh
sudo chmod +x /opt/scripts/auto-update.sh
Schedule it with cron. To run it every night at 2am, open rootâs crontab:
sudo crontab -e
Then add:
# Run the script at 2 AM every day to keep the system updated
0 2 * * * /opt/scripts/auto-update.sh >> /var/log/update-script.log 2>&1
# Run the script at boot so it carries on if the system was rebooted during an update
@reboot /opt/scripts/auto-update.sh >> /var/log/update-script.log 2>&1
The first line is the nightly 2am run that does the regular updates.
The @reboot line is the important one. If the server reboots part way through an update, whether the script rebooted it or someone did it by hand, this makes sure the script starts again on boot and finishes the job. On a normal boot thereâs no progress file, so it starts a full run from the beginning: it installs anything thatâs waiting and reboots again if an update needs it. If youâd rather it only ran at 2am, leave the @reboot line out, but then a run thatâs interrupted wonât finish until the next night.
Discord report (optional). In Discord, create a webhook for a channel (channel settings, Integrations, Webhooks), then save its URL where only root can read it:
sudo install -d -m 0700 /etc/auto-update
echo 'https://discord.com/api/webhooks/<id>/<token>' | sudo tee /etc/auto-update/discord-webhook >/dev/null
sudo chmod 600 /etc/auto-update/discord-webhook
Without that file the script still patches as normal and posts nothing.
Running it by hand. You can also run it yourself at any time:
sudo /opt/scripts/auto-update.sh
Worth knowing
- Logs. With the cron setup above, everything goes to
/var/log/update-script.log. Itâs worth reading the first few runs. - Discord. A report only goes out when something changed, the server rebooted or a step failed. Its title tells you whether the server patched cleanly, still has updates pending or had failures, and the footer shows the kernel itâs running.
- Permissions. The script runs commands like
aptandreboot, so it needs root. - If something goes wrong. If another apt run (or unattended-upgrades) is busy, it waits up to 10 minutes rather than failing. When a package ships a new default config file, it keeps yours. If an apt step still fails, the run ends with âfinished with N failed apt step(s)â instead of âcompleted successfullyâ, so the log tells you.
- Debian. Ubuntu flags a needed reboot itself. On Debian the script also reboots when a newer kernel is installed than the one running, once per kernel version.
- A manual reboot mid-run means it carries on from where it was on the next boot, rather than starting again. To force a clean run, delete
/var/lib/update-script/progressfirst. - Test it first. Run it by hand once before you hand it over to cron, so you know it behaves on your server.
Once thatâs in place your server keeps itself patched, which cuts down your exposure to security holes and means youâre always on the latest fixes. If you want to see how much is out there probing for those holes, my live attack map shows what Cloudflare blocks on my own sites.
FAQ
Should I use this or unattended-upgrades?
If you only want security updates, and youâre happy for kept back packages to wait, unattended-upgrades is built in and does that well. If you want every update installed, kept back and phased packages included, with reboots handled for you, use this script. You donât need both. If you keep unattended-upgrades switched on as well, run this script at a different time so the two donât try to use apt at once.
How do I stop one package, like Docker, from being upgraded?
Put it on hold:
sudo apt-mark hold docker-ce docker-ce-cli containerd.io
The upgrade steps leave held packages alone, and the one-at-a-time step logs âFailed to installâ for each held package and moves on to the next. When youâre ready to update it yourself, run sudo apt-mark unhold with the same package names. apt-mark showhold lists everything thatâs on hold.
Disclaimer
Before you run any automated update script, make sure youâve got backups you trust. Regular backups are the thing that gets you out of trouble when something unexpected happens.
This script is designed to apply updates safely and cope with reboots along the way, but automatic updates always carry some risk.
You use this script at your own risk. I canât take responsibility for any damage, data loss or downtime that comes from running it. Please make sure you have full backups before using this, or any other automation, on your systems.
What to read next
3 pages
Related reading
1 page
Got a question about this, or built something similar? Get in touch. New write-ups go out on the RSS feed and LinkedIn, everything I've built is on the projects page, and my free calculators and guides are on the tools page.