Environment Preflight Check: Refuse to Start in a Broken World

Status: active

Covered by a 79-test automated suite and run end to end on a lab workstation (Ubuntu 26.04); not yet deployed on a schedule.

Bash 5 GNU coreutils timedatectl or chronyc for clock checks

The problem

Scripts fail in two places: in their logic, or in the assumptions they made about the world before line one. The second kind is more common, more preventable, and produces far worse error messages, because the script discovers a missing dependency at whatever line happens to need it, forty seconds in, possibly after mutating state, and reports it in whatever confusing dialect that line speaks. The reliability library fixed this for my bash tools with a require_commands function, and the pattern immediately wanted to grow: paths, variables, disk space, clock sync. Rather than growing a bash function into a monster, the assumptions moved into a file of their own.

That relocation is the actual idea here. A manifest of assumptions, sitting next to the script it protects, is documentation that executes. New host, new teammate, three years of forgetting later: the answer to "what does this job need to run" is no longer archaeology through the script body. It is a seven-line file that also happens to be enforced.

The manifest

Plain text in a regular file, one assumption per line, tokens separated by spaces or tabs, comments and blank lines ignored, and at least one directive required. Each directive takes exactly its arguments, no more and no fewer:

# nightly_report.preflight
command   curl
command   jq
readable  /etc/nightly_report/config.json
writable  /var/lib/nightly_report
variable  REPORT_RECIPIENT
disk_space /var/lib/nightly_report 500
clock_sync

Seven directives cover the assumptions that actually break jobs: command (a program name found on PATH, not a path; a shell builtin, keyword, or function does not count), readable and writable (a path that passes the read or write permission test, which is false on a read-only mount; a directory must also grant search permission, since creating a file in it needs both), directory (exists and is one), variable (exported into the environment and non-empty; the name must be a valid shell variable name and must not begin with preflight_, which the checker reserves for its own variables), disk_space (path and minimum free MiB, a whole number of 1 to 15 digits; free space is read in bytes and rounded down, so 1 byte short fails), and clock_sync (the system clock is NTP-synchronized, because log timestamps and time-limited credentials both depend on it).

Design decisions

Every failed check reported, then one exit. The tool never stops at the first failed check. A host missing three dependencies produces a report naming all three, because fix-rerun-fix-rerun against a checker that reveals one failure per run is a specific misery everyone has lived and nobody should inflict. The same goes for the manifest itself: every line is validated before any check runs, so a manifest with three typos reports all three, and nothing is checked against a contract that is half broken.

An unverifiable check is a failed check. If the manifest asks for clock_sync and neither timedatectl nor chronyc can confirm synchronization, the check fails with that explanation, it does not skip. Each tool must be a real program on PATH, must exit 0, and must say the clock is synchronized; when the first cannot answer, as in a container with no systemd bus, the second is tried. A preflight that silently waives what it cannot verify converts the manifest from a contract into a suggestion. If a given host genuinely should not verify something, the honest move is removing the line for that deployment, which is a visible decision instead of an invisible one.

Exit codes follow the house convention. 0 all checks passed, 1 one or more failed, 2 the checker was given other than exactly one argument, or the manifest itself is missing, unreadable (including a read error partway through), a directory or other non-regular file, empty of checks, or malformed, including any directive the tool does not recognize and any line with the wrong number of arguments. A manifest that holds no checks proves nothing, so a file truncated to zero bytes by a failed deploy stops the job instead of waving it through. A typo or a stray extra word in the manifest is a loud error, not a skipped line, for the same reason as above: unknown directives that pass silently are checks you believe exist and do not.

The checker changes nothing. No directory creation, no fixing, no helpful remediation, no probe files, and sourcing it for tests runs no manifest and leaves the caller's shell options alone. Running it always runs the checks; no environment variable switches them off. The report says what is wrong; a human or the calling script decides what to do about it. A preflight with side effects is a second thing to preflight.

The script

#!/usr/bin/env bash
#
# ---------------------------------------------------------------------
# Path:         preflight_check.sh
# Filename:     preflight_check.sh
# Project:      preflight_check
# Description:  Verify environment assumptions declared in a manifest.
#               The whole manifest is validated first; then every check
#               runs and every failed check is reported, then one exit.
# Status:       lab-tested
# Revision:     6
# Updated:      2026-11-11
# Requires:     Bash 4.2 or newer, GNU coreutils (df), and one of
#               timedatectl or chronyc when clock_sync is used
# Included by:  standalone command line tool; sourceable for testing
# Provides:     check_command_exists, check_path_readable,
#               check_path_writable, check_directory_exists,
#               check_variable_set, check_disk_space,
#               check_clock_synchronized, run_manifest
# ---------------------------------------------------------------------
#
# Portability
#   Target shells:  bash 4.2+ (uses arrays and indirect expansion).
#   Tested on:      bash 5.3.9 on Ubuntu 26.04.1.
#   df --output is GNU coreutils 8.21+ and is required. On BSD or
#   busybox userlands the disk_space directive will report a hard
#   failure rather than a wrong answer.
#
# Usage:
#   bash preflight_check.sh <manifest_file>
#
# Exit codes:
#   0  every check passed (at least one check ran)
#   1  one or more checks failed
#   2  manifest missing, unreadable, not a regular file, holding no
#      checks, or malformed; every malformed line is reported and no
#      check runs
#
# Sourcing:
#   Sourcing the file (for tests) only defines its functions and its
#   preflight_ globals; it never runs a manifest and does not change
#   shell options. Running it with bash always runs the manifest, so an
#   inherited PREFLIGHT_LIB_ONLY cannot switch the check off. Variable
#   names beginning with preflight_ are reserved for the checker.
#

preflight_failure_messages=();
preflight_checks_run=0;

add_failure() {
    preflight_failure_messages+=("${1}");
};

is_valid_variable_name() {
    [[ "${1}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]];
};

# A minimum of up to 15 digits stays far below the largest integer Bash can
# compare (2^63 - 1, 19 digits). The limit is deliberately conservative: an
# unbounded figure could overflow, make the test command return 2 instead
# of 0 or 1, and read as "enough space".
is_valid_megabyte_figure() {
    [[ "${1}" =~ ^[0-9]{1,15}$ ]];
};

# True only for a variable carrying the export attribute, which is what a
# job started from this environment would receive. A plain shell variable,
# including this file's own globals, does not count.
is_exported_variable() {
    local preflight_variable_declaration;
    preflight_variable_declaration="$(declare -p "${1}" 2>/dev/null)" || return 1;
    [[ "${preflight_variable_declaration}" =~ ^declare\ -[A-Za-z]*x ]];
};

# ---------------------------------------------------------------------
# Individual checks. Each records failures; none exit on its own.
# ---------------------------------------------------------------------

# type -P searches PATH only. command -v would also accept a shell builtin,
# a keyword, an alias, or one of this file's own functions, none of which
# is a program the job can run from PATH. A name with a slash is a path,
# which type -P would accept without searching PATH at all, and -- keeps a
# name such as -a from being read as an option to type.
check_command_exists() {
    if [[ "${1}" == */* ]]; then
        add_failure "command: expects a program name, not a path: ${1}";
        return;
    fi;
    type -P -- "${1}" > /dev/null 2>&1 \
        || add_failure "command not found in PATH: ${1}";
};

check_path_readable() {
    [ -r "${1}" ] || add_failure "not readable (missing or permissions): ${1}";
};

# -w is a permission test. It is false on a read-only mount, even as root,
# but it cannot promise that a later write succeeds (a full disk or a quota
# can still refuse it). The checker does not write a probe file. Creating a
# file in a directory needs search permission as well as write permission,
# so a directory must pass -x too.
check_path_writable() {
    if [ -d "${1}" ]; then
        { [ -w "${1}" ] && [ -x "${1}" ]; } \
            || add_failure "not writable: ${1} (a directory needs write and search permission)";
        return;
    fi;
    [ -w "${1}" ] || add_failure "not writable: ${1}";
};

check_directory_exists() {
    [ -d "${1}" ] || add_failure "not a directory: ${1}";
};

# The name is checked before indirect expansion. ${!name} treats a token
# such as x[$(command)] as an array subscript and runs the command, and an
# invalid name aborts the whole run. Bash scopes locals dynamically, so a
# name used by this file could be read instead of the job's variable; every
# name on this call path begins with preflight_, and that prefix is refused.
check_variable_set() {
    local preflight_variable_value;
    if ! is_valid_variable_name "${1}"; then
        add_failure "variable: not a valid shell variable name: ${1}";
        return;
    fi;
    if [[ "${1}" == preflight_* ]]; then
        add_failure "variable: names beginning with preflight_ are reserved by the checker: ${1}";
        return;
    fi;
    if ! is_exported_variable "${1}"; then
        add_failure "variable not set in the environment (unset or not exported): ${1}";
        return;
    fi;
    preflight_variable_value="${!1:-}";
    [ -n "${preflight_variable_value}" ] || add_failure "variable unset or empty: ${1}";
};

# check_disk_space <path> <minimum_megabytes>
#
# An unverifiable check is a failed check. The previous implementation
# tested the exit status of a pipeline ending in tr, which succeeds even
# when df fails, so an unstattable path produced an empty reading, a
# silenced integer comparison error, and a PREFLIGHT OK verdict. The
# reading is now captured and validated before it is compared. The -- ends
# df's options, so a path such as -a is a path, not "list every filesystem".
# df reads in bytes and is rounded down to whole MiB here: with
# --block-size=1M, df rounds up, so 1 byte short of the minimum would pass.
check_disk_space() {
    local target_path="${1}";
    local minimum_megabytes="${2}";
    local df_output;
    local available_bytes;
    local available_megabytes;

    if ! df_output="$(df --output=avail --block-size=1 -- "${target_path}" 2>/dev/null)"; then
        add_failure "disk_space: cannot read free space for ${target_path} (path missing or df unsupported)";
        return;
    fi;

    available_bytes="$(printf '%s\n' "${df_output}" | tail -n 1 | tr -d ' ')";

    # Both figures are bounded before they are used, so neither the
    # division nor the comparison can overflow. 18 digits of bytes is just
    # under one exbibyte; a larger reading fails as unreadable.
    if ! [[ "${available_bytes}" =~ ^[0-9]{1,18}$ ]]; then
        add_failure "disk_space: unreadable free-space value for ${target_path}";
        return;
    fi;
    available_megabytes=$(( 10#${available_bytes} / 1048576 ));

    if ! is_valid_megabyte_figure "${minimum_megabytes}"; then
        add_failure "disk_space: minimum \"${minimum_megabytes}\" is not a whole number of megabytes (1 to 15 digits)";
        return;
    fi;

    if [ "${available_megabytes}" -lt "${minimum_megabytes}" ]; then
        add_failure "disk_space: ${target_path} has ${available_megabytes}MB free, need ${minimum_megabytes}MB";
    fi;
};

# Each verifier is a program found on PATH (type -P) and run by its full
# path, so a shell function of the same name is never what answers. The
# tool's own exit status must be 0 and its output must confirm
# synchronization. If the first verifier cannot confirm it (no systemd bus
# in a container, for example), the second is still tried.
check_clock_synchronized() {
    local timedatectl_path;
    local chronyc_path;
    local clock_output;
    local verifiers_tried="";

    timedatectl_path="$(type -P timedatectl 2>/dev/null)" || timedatectl_path="";
    if [ -n "${timedatectl_path}" ]; then
        verifiers_tried="timedatectl";
        if clock_output="$("${timedatectl_path}" show --property=NTPSynchronized --value 2>/dev/null)" \
            && [ "${clock_output}" = "yes" ]; then
            return;
        fi;
    fi;

    chronyc_path="$(type -P chronyc 2>/dev/null)" || chronyc_path="";
    if [ -n "${chronyc_path}" ]; then
        verifiers_tried="${verifiers_tried:+${verifiers_tried} and }chronyc";
        if clock_output="$("${chronyc_path}" tracking 2>/dev/null)" \
            && printf '%s\n' "${clock_output}" | grep -q '^Leap status.*Normal'; then
            return;
        fi;
    fi;

    if [ -z "${verifiers_tried}" ]; then
        add_failure "clock_sync: no verification tool available (timedatectl, chronyc); unverifiable counts as failed";
        return;
    fi;
    add_failure "clock_sync: ${verifiers_tried} could not confirm NTP synchronization (not synchronized, or the tool failed)";
};

# ---------------------------------------------------------------------
# Manifest handling
# ---------------------------------------------------------------------

# The manifest path is held here rather than passed into the loop body.
# ShellCheck pairs a `done < "${file}"` read against the same variable used
# beside a redirect inside the loop and reports SC2094; holding it once
# removes the pairing without weakening anything.
preflight_manifest_path="";

# manifest_error <line_number> <message>
# A malformed manifest is a loud error, never a skipped line. A directive
# that silently does nothing is a check you believe exists and does not.
manifest_error() {
    printf 'preflight_check: %s at %s line %d\n' \
        "${2}" "${preflight_manifest_path}" "${1}" >&2;
    return 2;
};

# validate_manifest_line <line_number> <token_count> <directive> <first> <second>
# Returns 0 for a well-formed line, 2 after printing why it is not.
validate_manifest_line() {
    local line_number="${1}";
    local token_count="${2}";
    local directive_name="${3}";
    local first_argument="${4}";
    local second_argument="${5}";

    case "${directive_name}" in
        command|readable|writable|directory|variable)
            if [ "${token_count}" -ne 2 ]; then
                manifest_error "${line_number}" \
                    "directive \"${directive_name}\" takes exactly one argument, found $((token_count - 1))";
                return 2;
            fi;
            if [ "${directive_name}" = "variable" ] && ! is_valid_variable_name "${first_argument}"; then
                manifest_error "${line_number}" \
                    "variable name \"${first_argument}\" is not a valid shell variable name";
                return 2;
            fi;
            if [ "${directive_name}" = "variable" ] && [[ "${first_argument}" == preflight_* ]]; then
                manifest_error "${line_number}" \
                    "variable names beginning with preflight_ are reserved by the checker: \"${first_argument}\"";
                return 2;
            fi;
            if [ "${directive_name}" = "command" ] && [[ "${first_argument}" == */* ]]; then
                manifest_error "${line_number}" \
                    "directive \"command\" takes a program name, not a path: \"${first_argument}\"";
                return 2;
            fi;
            ;;
        disk_space)
            if [ "${token_count}" -ne 3 ]; then
                manifest_error "${line_number}" \
                    "directive \"disk_space\" takes a path and a minimum in megabytes, found $((token_count - 1)) arguments";
                return 2;
            fi;
            if ! is_valid_megabyte_figure "${second_argument}"; then
                manifest_error "${line_number}" \
                    "disk_space minimum \"${second_argument}\" is not a whole number of megabytes (1 to 15 digits)";
                return 2;
            fi;
            ;;
        clock_sync)
            if [ "${token_count}" -ne 1 ]; then
                manifest_error "${line_number}" \
                    "directive \"clock_sync\" takes no arguments";
                return 2;
            fi;
            ;;
        *)
            manifest_error "${line_number}" \
                "unknown directive \"${directive_name}\"";
            return 2;
            ;;
    esac;
    return 0;
};

# run_manifest <manifest_file>
# Returns 0 all passed, 1 failures recorded, 2 manifest problem.
#
# Two passes. The first reads and validates every line and reports every
# malformed one; if any is malformed, no check runs, so a broken contract
# is never partly executed and no check result is discarded. The second
# runs the checks and records every failure.
run_manifest() {
    local preflight_manifest_file="${1:-}";
    local preflight_line_number=0;
    local preflight_manifest_line="";
    local -a preflight_manifest_tokens=();
    local preflight_token_count;
    local preflight_malformed_line_count=0;
    local -a preflight_parsed_directives=();
    local -a preflight_parsed_first_arguments=();
    local -a preflight_parsed_second_arguments=();
    local preflight_check_index;

    preflight_failure_messages=();
    preflight_checks_run=0;
    preflight_manifest_path="${preflight_manifest_file}";

    if [ -z "${preflight_manifest_file}" ] || [ ! -r "${preflight_manifest_file}" ]; then
        printf 'usage: bash preflight_check.sh <manifest_file> (file must be readable)\n' >&2;
        return 2;
    fi;
    # A directory passes the -r test above, then every read fails. Refused
    # here so it is reported as a manifest problem (2), not a crash.
    if [ -d "${preflight_manifest_file}" ]; then
        printf 'preflight_check: manifest is a directory, not a file: %s\n' "${preflight_manifest_file}" >&2;
        return 2;
    fi;
    # A FIFO blocks until a writer appears and /dev/zero never ends, so a
    # preflight given either would hang instead of answering. Only a
    # regular file (or a symlink to one) is read.
    if [ ! -f "${preflight_manifest_file}" ]; then
        printf 'preflight_check: manifest is not a regular file: %s\n' "${preflight_manifest_file}" >&2;
        return 2;
    fi;
    # Bash's read reports an I/O error the same way as end of file, so a
    # file that fails partway would be parsed as a shorter manifest. One
    # full read first turns any read error into a manifest problem.
    if ! cat -- "${preflight_manifest_file}" > /dev/null 2>&1; then
        printf 'preflight_check: manifest could not be read in full: %s\n' "${preflight_manifest_file}" >&2;
        return 2;
    fi;

    while IFS= read -r preflight_manifest_line || [ -n "${preflight_manifest_line}" ]; do
        preflight_line_number=$((preflight_line_number + 1));
        # A file saved with CRLF endings carries a carriage return at the
        # end of each line; it is removed so "bash\r" is read as "bash".
        preflight_manifest_line="${preflight_manifest_line%$'\r'}";
        preflight_manifest_line="${preflight_manifest_line%%#*}";
        # Split on spaces and tabs only, whatever IFS the caller exported.
        # Every token is kept, so a stray extra token can be counted and
        # refused instead of riding along unchecked.
        IFS=$' \t' read -r -a preflight_manifest_tokens <<< "${preflight_manifest_line}" || true;
        preflight_token_count="${#preflight_manifest_tokens[@]}";
        [ "${preflight_token_count}" -eq 0 ] && continue;
        if ! validate_manifest_line "${preflight_line_number}" "${preflight_token_count}" \
            "${preflight_manifest_tokens[0]}" "${preflight_manifest_tokens[1]:-}" "${preflight_manifest_tokens[2]:-}"; then
            preflight_malformed_line_count=$((preflight_malformed_line_count + 1));
            continue;
        fi;
        preflight_parsed_directives+=("${preflight_manifest_tokens[0]}");
        preflight_parsed_first_arguments+=("${preflight_manifest_tokens[1]:-}");
        preflight_parsed_second_arguments+=("${preflight_manifest_tokens[2]:-}");
    done < "${preflight_manifest_file}";

    if [ "${preflight_malformed_line_count}" -gt 0 ]; then
        printf 'preflight_check: %d malformed line(s) in %s; no checks were run\n' \
            "${preflight_malformed_line_count}" "${preflight_manifest_file}" >&2;
        return 2;
    fi;
    # A manifest with no checks proves nothing. A file truncated to zero
    # bytes by a failed deploy must stop the job, not wave it through.
    if [ "${#preflight_parsed_directives[@]}" -eq 0 ]; then
        printf 'preflight_check: manifest contains no checks: %s\n' "${preflight_manifest_file}" >&2;
        return 2;
    fi;

    for preflight_check_index in "${!preflight_parsed_directives[@]}"; do
        preflight_checks_run=$((preflight_checks_run + 1));
        case "${preflight_parsed_directives[${preflight_check_index}]}" in
            command)    check_command_exists     "${preflight_parsed_first_arguments[${preflight_check_index}]}" ;;
            readable)   check_path_readable      "${preflight_parsed_first_arguments[${preflight_check_index}]}" ;;
            writable)   check_path_writable      "${preflight_parsed_first_arguments[${preflight_check_index}]}" ;;
            directory)  check_directory_exists   "${preflight_parsed_first_arguments[${preflight_check_index}]}" ;;
            variable)   check_variable_set       "${preflight_parsed_first_arguments[${preflight_check_index}]}" ;;
            disk_space) check_disk_space         "${preflight_parsed_first_arguments[${preflight_check_index}]}" "${preflight_parsed_second_arguments[${preflight_check_index}]}" ;;
            clock_sync) check_clock_synchronized ;;
        esac;
    done;

    [ "${#preflight_failure_messages[@]}" -gt 0 ] && return 1;
    return 0;
};

report_and_exit() {
    local manifest_file="${1}";
    local manifest_status="${2}";

    case "${manifest_status}" in
        0)
            printf 'PREFLIGHT OK: %d checks passed (%s)\n' \
                "${preflight_checks_run}" "${manifest_file}";
            exit 0;
            ;;
        1)
            printf 'PREFLIGHT FAILED: %d of %d checks (%s)\n' \
                "${#preflight_failure_messages[@]}" "${preflight_checks_run}" "${manifest_file}";
            printf '  - %s\n' "${preflight_failure_messages[@]}";
            exit 1;
            ;;
        2)
            exit 2;
            ;;
        *)
            # Only 0, 1, and 2 are defined. Anything else is not a pass.
            printf 'preflight_check: unexpected internal status %s for %s\n' \
                "${manifest_status}" "${manifest_file}" >&2;
            exit 2;
            ;;
    esac;
};

# The manifest runs only when the file is executed. (return) succeeds only
# when the file is being sourced, so sourcing never runs a manifest and an
# inherited environment variable cannot turn an executed run into a silent
# exit 0. set -u applies to the executed run only, so sourcing never
# changes the caller's shell options.
if ! (return 0 2>/dev/null); then
    set -u;
    if [ "${#}" -ne 1 ]; then
        printf 'usage: bash preflight_check.sh <manifest_file> (exactly one argument)\n' >&2;
        exit 2;
    fi;
    preflight_manifest_argument="${1}";
    run_manifest "${preflight_manifest_argument}";
    report_and_exit "${preflight_manifest_argument}" "${?}";
fi;

Using it

# In front of a job, cron or otherwise: refuse to start in a broken world
bash preflight_check.sh /etc/nightly_report/nightly_report.preflight || exit "${?}";
/usr/local/bin/nightly_report.sh;

The composition with the exit code convention is the payoff: a wrapper can distinguish "the environment is broken" (1) from "the manifest is broken" (2) from "proceed" (0), and the validator or any monitoring wrapper treats a persistent preflight failure like any other alertable condition.

Known limitations

The variable directive checks the checker's own environment, so under cron the manifest must be checked by the same invocation context that runs the job, which is the correct place anyway but worth stating. disk_space trusts df and inherits its view of the filesystem, including any staleness on hung network mounts; a hung mount will stall the check, and running the checker under timeout in cron contexts is the sensible dressing. Tokens are split on spaces and tabs and everything after # is a comment, so a path containing a space, a tab, or # cannot be expressed. writable is a permission test: a later write can still fail on a full disk or a quota. The checks answer for the user who runs the checker, so run it as the job's user. No remediation and no configuration flags, both on purpose; the manifest is the entire interface.

Roadmap

A reachable directive (host and port) that would fold the validator's rung-two check into manifests for network-dependent jobs. A --quiet flag for wrappers that only want the exit code. Possibly a manifest linter, though the unknown-directive hard failure covers most of what a linter would.