Automating Updates on Ubuntu and Debian

Su Suriya Ravichandran Updated 06 Dec 2026
22 min read ·Lesson 169 of 205

Keeping software up to date is one of the most effective ways to protect a server: most security incidents exploit flaws for which a fix was already published. Updating by hand is easy to forget, though, and on a fleet of servers it does not scale. Ubuntu and Debian manage software with the APT package system, and APT can be driven completely from a script. This lesson explains how APT updates work, what goes wrong when updates run without a person at the keyboard, how Ubuntu and Debian's own unattended-upgrades service handles it, and how to write a Bash update script that runs safely on a schedule.

All commands that change packages need root rights. In the examples, sudo is left out because they were run as root.

How APT Updates Work

APT works in two separate steps:

  1. Refresh the package lists. apt-get update downloads, from every repository configured in /etc/apt/sources.list and /etc/apt/sources.list.d/, the list of packages and versions the repository currently offers. It installs nothing; it only updates APT's knowledge of what is available.
  2. Install newer versions. apt-get upgrade compares the installed versions with the refreshed lists and installs the newer ones.

Running upgrade without update first only installs updates that APT already knew about, so a script always runs both, in this order.

There are two kinds of upgrade:

CommandWhat it does
apt-get upgradeupgrades installed packages, but never removes a package and never installs a new one; an upgrade that needs either is kept back
apt-get full-upgrade (also dist-upgrade)upgrades everything, installing or removing packages when dependencies change

upgrade is the conservative choice for unattended runs. On Ubuntu, for example, a new kernel arrives as a new package, which plain upgrade keeps back; full-upgrade installs it. Neither command moves the system to a new release of Ubuntu or Debian; that is a separate, deliberate procedure (do-release-upgrade on Ubuntu).

apt or apt-get?

apt is the newer, friendlier command for people, with progress bars and colors. apt-get (and apt-cache) are the older commands whose output and options are kept stable. apt itself warns when its output is not a terminal:

apt list --upgradable | cat

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Listing...
gc-kernel-sim/unknown 1.1 all [upgradable from: 1.0]
gc-tool/unknown 2.1 all [upgradable from: 2.0]
gc-webapp/unknown 1.1 all [upgradable from: 1.0]

Scripts should use apt-get.

The test system for this lesson

To show real upgrades without changing a production machine, the examples use three small test packages, gc-webapp, gc-kernel-sim and gc-tool, built with dpkg-deb. Their old versions are installed, and a local repository (a folder with a Packages.gz index, listed as deb [trusted=yes] file:/srv/t169/repo ./) offers newer ones. The packages are designed to reproduce real situations:

  • gc-webapp ships a configuration file, /etc/gc-webapp/gc-webapp.conf, which the administrator has changed locally; the new version ships a changed default.
  • gc-kernel-sim behaves like a kernel update: its installation script marks the system as needing a restart.
  • gc-tool is used to show held packages.

Because the repository is a local folder, apt-get update prints file: addresses where a real system shows http://archive.ubuntu.com/... or http://deb.debian.org/..., and the Ign lines only mean that this test repository has no signed Release file.

Checking for Updates

apt-get update
Get:1 file:/srv/t169/repo ./ InRelease
Ign:1 file:/srv/t169/repo ./ InRelease
Get:2 file:/srv/t169/repo ./ Release
Ign:2 file:/srv/t169/repo ./ Release
Get:3 file:/srv/t169/repo ./ Packages [520 B]
Reading package lists...

To see what an upgrade would do without doing it, add -s (--simulate). The lines starting with Inst are the packages that would be installed, with the current version in square brackets and the new one in parentheses:

apt-get -s upgrade
Reading package lists...
Building dependency tree...
Reading state information...
Calculating upgrade...
The following packages will be upgraded:
  gc-kernel-sim gc-tool gc-webapp
3 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Inst gc-kernel-sim [1.0] (1.1 localhost [all])
Inst gc-tool [2.0] (2.1 localhost [all])
Inst gc-webapp [1.0] (1.1 localhost [all])
Conf gc-kernel-sim (1.1 localhost [all])
Conf gc-tool (2.1 localhost [all])
Conf gc-webapp (1.1 localhost [all])

apt-get -s upgrade | awk '/^Inst / { print $2 }' turns this into a plain list of package names, which is the form a script needs. A simulation does not need the package lock, so it can run while other APT commands are busy.

Holding packages

Sometimes one package must stay at its current version, for example while an application is tested against a new database release. apt-mark hold stops APT from upgrading it:

apt-mark hold gc-tool
apt-get -s upgrade | grep -E "^Inst|kept back|upgraded,"
apt-mark unhold gc-tool
gc-tool set on hold.
The following packages have been kept back:
2 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
Inst gc-kernel-sim [1.0] (1.1 localhost [all])
Inst gc-webapp [1.0] (1.1 localhost [all])
Canceled hold on gc-tool.

The held package appears under "kept back" (its name is on the next line, which the grep pattern did not select) and is counted as "not upgraded". apt-mark showhold lists all held packages. A hold that is forgotten blocks security fixes for that package forever, so update reports should mention kept-back packages.

Why Updates Need Care When Nobody Is Watching

An interactive upgrade can stop and ask questions. In a scheduled script there is nobody to answer, so every possible question must be answered in advance.

-y answers APT, not dpkg

-y (--yes) answers "yes" to APT's own "Do you want to continue?" question. It does not answer questions asked later by dpkg, the lower-level tool that unpacks and configures each package. The most important dpkg question is about configuration files ("conffiles"): when a package ships a new version of a configuration file that the administrator has changed, dpkg asks which version to keep.

Here is an upgrade run as a script would run it, with -y and with standard input not connected to a terminal (< /dev/null):

apt-get -y upgrade < /dev/null; echo "[status $?]"
...
Setting up gc-kernel-sim (1.1) ...
Setting up gc-tool (2.1) ...
Setting up gc-webapp (1.1) ...

Configuration file '/etc/gc-webapp/gc-webapp.conf'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** gc-webapp.conf (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package gc-webapp (--configure):
 end of file on stdin at conffile prompt
Errors were encountered while processing:
 gc-webapp
E: Sub-process /usr/bin/dpkg returned an error code (1)
[status 100]

(The first lines of the output are left out.) dpkg asked the question, read end-of-file instead of an answer, and stopped. The package is left unpacked but not configured, and apt-get exits with status 100. If standard input had been a terminal with nobody watching, the upgrade would instead have waited forever, holding the package lock. dpkg -l shows the broken state in its first column, and dpkg --audit explains it:

dpkg -l gc-webapp | tail -1
dpkg --audit
iU  gc-webapp      1.1          all          test package gc-webapp for the GoCourse apt lesson
The following packages have been unpacked but not yet configured.
They must be configured using dpkg --configure or the configure
menu option in dselect for them to work:
 gc-webapp            test package gc-webapp for the GoCourse apt lesson

ii means installed and configured; iU means installed but only unpacked.

DEBIAN_FRONTEND=noninteractive

Many packages ask setup questions through debconf, a separate question system (for example, a time zone or a mail server type). Setting the environment variable DEBIAN_FRONTEND=noninteractive makes debconf use default answers without asking. It does not affect dpkg's configuration file question: running the same upgrade with DEBIAN_FRONTEND=noninteractive apt-get -y upgrade < /dev/null failed with exactly the same "end of file on stdin at conffile prompt" error and status 100.

Answering the configuration file question

dpkg's --force-conf* options answer the question in advance. APT passes options to dpkg with -o Dpkg::Options::=OPTION:

dpkg optionEffect
--force-confdefif the question has a default answer, use it without asking
--force-confoldkeep the currently installed (locally changed) file
--force-confnewinstall the package maintainer's new file

The usual combination for unattended upgrades is --force-confdef --force-confold: use dpkg's default where there is one, and otherwise keep the local file, so an update never silently overwrites the administrator's settings. The new default file is saved next to it with the extension .dpkg-dist, so it can be compared later.

The half-configured package from above can be finished with these options:

DEBIAN_FRONTEND=noninteractive dpkg --configure -a --force-confdef --force-confold < /dev/null
dpkg -l gc-webapp | tail -1
ls /etc/gc-webapp/
cat /etc/gc-webapp/gc-webapp.conf
cat /etc/gc-webapp/gc-webapp.conf.dpkg-dist
Setting up gc-webapp (1.1) ...

Configuration file '/etc/gc-webapp/gc-webapp.conf'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
 ==> Keeping old config file as default.
ii  gc-webapp      1.1          all          test package gc-webapp for the GoCourse apt lesson
gc-webapp.conf
gc-webapp.conf.dpkg-dist
port = 9090   # changed by the administrator
port = 8080
workers = 4

dpkg --configure -a configures every package that is unpacked but not configured. The local setting port = 9090 was kept, and the maintainer's new file, with its new workers setting, is waiting in gc-webapp.conf.dpkg-dist. Searching for *.dpkg-dist files after updates (find /etc -name '*.dpkg-dist') shows which configurations deserve a manual review.

The package lock

Only one program may change the package system at a time. APT and dpkg protect it with lock files, mainly /var/lib/dpkg/lock-frontend. If another program holds the lock, for example a desktop update tool or the system's own daily update job, apt-get fails immediately. In this test, a small Python program held the lock for 4 seconds:

apt-get -y autoremove; echo "[status $?]"
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2680 (python3)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
[status 100]

The option DPkg::Lock::Timeout (APT 1.9.11 and later, so Ubuntu 20.04, Debian 11 and newer) makes APT wait up to the given number of seconds instead:

SECONDS=0
apt-get -o DPkg::Lock::Timeout=10 -y autoremove; echo "[status $?, waited about ${SECONDS}s]"
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2680 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2680 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2680 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2680 (python3)...
Reading package lists...
Building dependency tree...
Reading state information...
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
[status 0, waited about 4s]

Never delete the lock files to "fix" this error; the lock exists because another process is changing the package database at that moment. Note that dpkg itself does not use this APT setting: in testing, dpkg --configure -a failed at once with "dpkg frontend lock was locked by another process" while the lock was held. A script that has to repair a half-installed system should therefore use apt-get -f install, which also configures unpacked packages but respects the lock timeout.

Restarts

Most updates take effect when the updated program is next started. A new kernel, however, only runs after a reboot, and updates to core libraries such as the C library are only fully used after the programs using them restart. On Ubuntu, packages that need a reboot create the file /var/run/reboot-required and add their names to /var/run/reboot-required.pkgs (this is the source of the "System restart required" message at login). The test package gc-kernel-sim does the same. Debian creates these files only when the corresponding packages are installed; the needrestart tool, available on both, can additionally list services that should be restarted. An update script should report a required restart and reboot only when that is explicitly allowed, at a time chosen for it.

The Built-in Solution: unattended-upgrades

Ubuntu installs, and Debian offers, the unattended-upgrades package for exactly this job. It is the recommended way to install security updates automatically. It is enabled with:

apt-get install unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades

This writes /etc/apt/apt.conf.d/20auto-upgrades:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

The values are intervals in days: refresh the lists and run unattended upgrades every day. The work is started by the systemd timers apt-daily.timer and apt-daily-upgrade.timer (systemctl list-timers 'apt-daily*' shows when they next run). What may be installed is configured in /etc/apt/apt.conf.d/50unattended-upgrades, for example:

Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::Package-Blacklist {
};
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

By default only the security repository is allowed. unattended-upgrade --dry-run --debug shows what it would do, and its logs are kept in /var/log/unattended-upgrades/. (The unattended-upgrades package was not installed on the machine used to test this lesson, so these settings are shown from its documentation and were not run here.)

unattended-upgrades is the right tool for routine security updates. A custom Bash script is useful when you want different rules: all updates instead of security updates only, upgrades at a specific maintenance window controlled by cron, a combined report, or steps before and after the upgrade such as a backup or a health check.

A Complete Example: An Unattended Update Script

auto-update.sh refreshes the package lists, shows what will be upgraded and what is kept back, upgrades without asking questions, keeps local configuration files, waits for the package lock, finishes interrupted installations, reports whether a restart is needed and can schedule one. Everything it prints is also appended to a log file with timestamps.

#!/usr/bin/env bash
#
# auto-update.sh - install available package updates on Ubuntu or Debian, unattended
#
# Usage: auto-update.sh [-n] [-f] [-r] [-l LOG_FILE]
#   -n  dry run: refresh the package lists and show what would be upgraded
#   -f  use full-upgrade (may install or remove packages to complete upgrades)
#   -r  reboot in 5 minutes if an update requires a restart
#   -l  log file (default: /var/log/auto-update.log)
#
# Exit status: 0 success, 1 an apt or dpkg step failed, 2 usage error or not root

set -uo pipefail

dry_run=0 mode=upgrade reboot=0 log_file=/var/log/auto-update.log
lock_file=/run/auto-update.lock

usage() { echo "usage: ${0##*/} [-n] [-f] [-r] [-l LOG_FILE]" >&2; exit 2; }
log()   { printf '%(%Y-%m-%d %H:%M:%S)T %s\n' -1 "$*"; }
fail()  { log "ERROR: $*"; exit 1; }

# Never ask questions; keep locally changed configuration files; wait up to
# 10 minutes if another apt or dpkg process (for example a desktop updater) is busy.
export DEBIAN_FRONTEND=noninteractive
apt_opts=(-q -y
          -o DPkg::Lock::Timeout=600
          -o Dpkg::Use-Pty=0
          -o Dpkg::Options::=--force-confdef
          -o Dpkg::Options::=--force-confold)

# held_back: print the packages apt would keep back (held or blocked)
held_back() {
    apt-get -s "$mode" 2>/dev/null |
        awk '/kept back:$/ { list = 1; next } list && /^ / { print; next } { list = 0 }' |
        xargs -r
}

run_update() {
    local -a pending
    local held

    exec 9> "$lock_file" || fail "cannot open $lock_file"
    flock -n 9 || fail "another auto-update.sh is already running"

    log "=== auto-update started (mode: $mode$( (( dry_run )) && echo ', dry run'))"

    # Finish anything an earlier, interrupted run left half-installed.
    # apt-get -f install configures such packages and, unlike dpkg, waits for the lock.
    if [[ -n $(dpkg --audit) ]]; then
        log "finishing interrupted package installations"
        apt-get "${apt_opts[@]}" -f install < /dev/null ||
            fail "apt-get -f install failed"
    fi

    log "refreshing package lists"
    apt-get "${apt_opts[@]}" update < /dev/null || fail "apt-get update failed"

    mapfile -t pending < <(apt-get -s "$mode" | awk '/^Inst / { print $2 }')
    held=$(held_back)
    log "${#pending[@]} package(s) to upgrade${pending[*]:+: ${pending[*]}}"
    [[ -n $held ]] && log "kept back (not upgraded): $held"

    if (( dry_run )); then
        log "dry run: nothing was changed"
    elif (( ${#pending[@]} > 0 )); then
        log "running apt-get $mode"
        apt-get "${apt_opts[@]}" "$mode" < /dev/null || fail "apt-get $mode failed"
        log "upgrade finished"
    fi

    if [[ -f /var/run/reboot-required ]]; then
        local by=''
        [[ -f /var/run/reboot-required.pkgs ]] &&
            by=$(sort -u /var/run/reboot-required.pkgs | xargs -r)
        log "a restart is required${by:+ (by: $by)}"
        if (( reboot && ! dry_run )); then
            log "rebooting in 5 minutes"
            shutdown -r +5 "auto-update.sh: restarting to finish updates" ||
                fail "could not schedule the reboot"
        elif (( reboot )); then
            log "dry run: would run: shutdown -r +5"
        fi
    fi

    log "=== auto-update finished"
}

while getopts ':nfrl:' opt; do
    case $opt in
        n) dry_run=1 ;;
        f) mode=full-upgrade ;;
        r) reboot=1 ;;
        l) log_file=$OPTARG ;;
        *) usage ;;
    esac
done
shift $(( OPTIND - 1 ))
(( $# == 0 )) || usage
(( EUID == 0 )) || { echo "${0##*/}: must be run as root" >&2; exit 2; }
command -v apt-get >/dev/null || { echo "${0##*/}: apt-get not found (not Debian/Ubuntu?)" >&2; exit 2; }
touch -- "$log_file" 2>/dev/null || { echo "${0##*/}: cannot write log file: $log_file" >&2; exit 2; }

# Show everything on screen and append it to the log at the same time
run_update 2>&1 | tee -a -- "$log_file"
exit "${PIPESTATUS[0]}"

How It Works

  • Checks before anything else. The script refuses to run unless it is root, apt-get exists and the log file can be written. These errors go to standard error with status 2, before logging starts.
  • Logging. All the real work happens in the function run_update, whose output (standard output and standard error together) is piped through tee -a, so it appears on screen and is appended to the log. log adds a timestamp with Bash's built-in printf '%(...)T' (lesson 115). Because run_update runs inside a pipeline, its exit status is taken from PIPESTATUS[0], not from tee.
  • One run at a time. flock -n on file descriptor 9 prevents two copies of the script from running together (lesson 171 covers lock files in detail). This is different from the APT lock: the script's own lock stops a second auto-update.sh, while DPkg::Lock::Timeout=600 makes each APT command wait up to 10 minutes for other package tools.
  • No questions. DEBIAN_FRONTEND=noninteractive is exported so debconf uses defaults; -y confirms APT's question; --force-confdef --force-confold answers dpkg's configuration file question by keeping local files; and every APT command reads from /dev/null, so any question that is still asked fails immediately instead of waiting forever. -q and Dpkg::Use-Pty=0 remove progress displays that would otherwise fill the log with partial lines.
  • Repairing first. If dpkg --audit reports anything, an earlier run was interrupted (a power cut, a full disk, a killed process). apt-get -f install finishes configuring those packages before new updates are installed.
  • Reporting. A simulated upgrade lists the packages that will be installed, and held_back extracts the "kept back" list from the same simulation output: awk starts printing after the line ending in kept back: and stops at the first line that does not start with a space; xargs -r joins the names on one line.
  • Restart. The script reads /var/run/reboot-required and the package names in /var/run/reboot-required.pkgs. Only with -r does it schedule a reboot, using shutdown -r +5, which warns logged-in users and can still be cancelled with shutdown -c. In a dry run it only says what it would do.

Running the Complete Example

The test system starts with the old package versions, the locally changed gc-webapp.conf, and gc-tool on hold. A dry run first (the APT output of update appears between the script's own timestamped lines):

$ apt-mark hold gc-tool
gc-tool set on hold.
$ auto-update.sh -n -l /srv/t169/auto-update.log
2026-11-24 15:12:43 === auto-update started (mode: upgrade, dry run)
2026-11-24 15:12:43 refreshing package lists
Get:1 file:/srv/t169/repo ./ InRelease
Ign:1 file:/srv/t169/repo ./ InRelease
Get:2 file:/srv/t169/repo ./ Release
Ign:2 file:/srv/t169/repo ./ Release
Get:3 file:/srv/t169/repo ./ Packages [520 B]
Reading package lists...
2026-11-24 15:12:43 2 package(s) to upgrade: gc-kernel-sim gc-webapp
2026-11-24 15:12:43 kept back (not upgraded): gc-tool
2026-11-24 15:12:43 dry run: nothing was changed
2026-11-24 15:12:43 === auto-update finished
status 0

The real run:

$ auto-update.sh -l /srv/t169/auto-update.log
2026-11-24 15:12:43 === auto-update started (mode: upgrade)
2026-11-24 15:12:43 refreshing package lists
Get:1 file:/srv/t169/repo ./ InRelease
Ign:1 file:/srv/t169/repo ./ InRelease
Get:2 file:/srv/t169/repo ./ Release
Ign:2 file:/srv/t169/repo ./ Release
Get:3 file:/srv/t169/repo ./ Packages [520 B]
Reading package lists...
2026-11-24 15:12:44 2 package(s) to upgrade: gc-kernel-sim gc-webapp
2026-11-24 15:12:44 kept back (not upgraded): gc-tool
2026-11-24 15:12:44 running apt-get upgrade
Reading package lists...
Building dependency tree...
Reading state information...
Calculating upgrade...
The following packages have been kept back:
  gc-tool
The following packages will be upgraded:
  gc-kernel-sim gc-webapp
2 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
Need to get 0 B/1358 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 file:/srv/t169/repo ./ gc-kernel-sim 1.1 [684 B]
Get:2 file:/srv/t169/repo ./ gc-webapp 1.1 [674 B]
debconf: delaying package configuration, since apt-utils is not installed
(Reading database ... 88415 files and directories currently installed.)
Preparing to unpack ..././gc-kernel-sim_1.1_all.deb ...
Unpacking gc-kernel-sim (1.1) over (1.0) ...
Preparing to unpack .../repo/./gc-webapp_1.1_all.deb ...
Unpacking gc-webapp (1.1) over (1.0) ...
Setting up gc-kernel-sim (1.1) ...
Setting up gc-webapp (1.1) ...

Configuration file '/etc/gc-webapp/gc-webapp.conf'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
 ==> Keeping old config file as default.
2026-11-24 15:12:44 upgrade finished
2026-11-24 15:12:44 a restart is required (by: gc-kernel-sim)
2026-11-24 15:12:44 === auto-update finished
status 0

The configuration file question was answered automatically by keeping the local file, the held package was left alone, and the script noticed the restart request. (The debconf: delaying package configuration line is specific to the minimal test system, where the optional apt-utils package is not installed.) The local setting survived:

$ cat /etc/gc-webapp/gc-webapp.conf
port = 9090   # changed by the administrator
$ ls /etc/gc-webapp
gc-webapp.conf
gc-webapp.conf.dpkg-dist

A dry run with -r shows the reboot decision without acting on it:

$ auto-update.sh -n -r -l /srv/t169/auto-update.log
2026-11-24 15:12:44 === auto-update started (mode: upgrade, dry run)
2026-11-24 15:12:44 refreshing package lists
Get:1 file:/srv/t169/repo ./ InRelease
Ign:1 file:/srv/t169/repo ./ InRelease
Get:2 file:/srv/t169/repo ./ Release
Ign:2 file:/srv/t169/repo ./ Release
Get:3 file:/srv/t169/repo ./ Packages [520 B]
Reading package lists...
2026-11-24 15:12:44 0 package(s) to upgrade
2026-11-24 15:12:44 kept back (not upgraded): gc-tool
2026-11-24 15:12:44 dry run: nothing was changed
2026-11-24 15:12:44 a restart is required (by: gc-kernel-sim)
2026-11-24 15:12:44 dry run: would run: shutdown -r +5
2026-11-24 15:12:44 === auto-update finished
status 0

(The real reboot path was not run on the test machine.) After apt-mark unhold gc-tool, a full-upgrade dry run includes the previously held package; the APT update lines are filtered out here:

$ auto-update.sh -f -n -l /srv/t169/auto-update.log
2026-11-24 15:12:51 === auto-update started (mode: full-upgrade, dry run)
2026-11-24 15:12:51 refreshing package lists
2026-11-24 15:12:52 1 package(s) to upgrade: gc-tool
2026-11-24 15:12:52 dry run: nothing was changed
2026-11-24 15:12:52 a restart is required (by: gc-kernel-sim)
2026-11-24 15:12:52 === auto-update finished

To test recovery, the system was reset to the old versions and broken on purpose with a plain apt-get -y upgrade < /dev/null, which failed at the configuration file question and left gc-webapp in the iU state. Then another program took the package lock for 5 seconds while the script started:

$ auto-update.sh -l /srv/t169/auto-update.log
2026-11-24 15:12:30 === auto-update started (mode: upgrade)
2026-11-24 15:12:30 finishing interrupted package installations
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 3237 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 3237 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 3237 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 3237 (python3)...
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 3237 (python3)...
Reading package lists...
Building dependency tree...
Reading state information...
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up gc-webapp (1.1) ...

Configuration file '/etc/gc-webapp/gc-webapp.conf'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
 ==> Keeping old config file as default.
2026-11-24 15:12:35 refreshing package lists
Get:1 file:/srv/t169/repo ./ InRelease
Ign:1 file:/srv/t169/repo ./ InRelease
Get:2 file:/srv/t169/repo ./ Release
Ign:2 file:/srv/t169/repo ./ Release
Get:3 file:/srv/t169/repo ./ Packages [520 B]
Reading package lists...
2026-11-24 15:12:35 0 package(s) to upgrade
2026-11-24 15:12:35 a restart is required (by: gc-kernel-sim)
2026-11-24 15:12:35 === auto-update finished
status 0

The script waited for the lock, finished configuring gc-webapp while keeping the local file, and found nothing left to upgrade, because the failed apt-get run had already unpacked all three new versions. (A first version of the script used dpkg --configure -a for this repair step; with the lock held it failed immediately, which is why the final script uses apt-get -f install.)

A second copy started while one is running, a non-root user, an unknown option and an unusable log file are all refused:

$ auto-update.sh -l /srv/t169/auto-update.log
2026-11-24 15:12:45 ERROR: another auto-update.sh is already running
status 1
$ setpriv --reuid=nobody --regid=nogroup --clear-groups ./auto-update.sh -n
auto-update.sh: must be run as root
status 2
$ auto-update.sh -x
usage: auto-update.sh [-n] [-f] [-r] [-l LOG_FILE]
status 2
$ auto-update.sh -l /no/such/dir/update.log
auto-update.sh: cannot write log file: /no/such/dir/update.log
status 2

The log keeps the whole history, including the refused second run:

$ tail -n 4 auto-update.log
2026-11-24 15:12:44 a restart is required (by: gc-kernel-sim)
2026-11-24 15:12:44 dry run: would run: shutdown -r +5
2026-11-24 15:12:44 === auto-update finished
2026-11-24 15:12:45 ERROR: another auto-update.sh is already running

Run weekly from root's crontab in a maintenance window (lesson 170), for example 30 3 * * 0 /usr/local/sbin/auto-update.sh -r, the script keeps a server current and restarts it only when an update requires it. The log file grows with every run, so add it to the rotation from lesson 165.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Automating Updates on Ubuntu and Debian and get answers drawn from it.

Signed-in readers only.