Build a Server Health-Check and Alert Script

Su Suriya Ravichandran Updated 06 Dec 2026
18 min read ·Lesson 202 of 205

This project builds healthcheck.sh, a script that reads a list of checks from a file, runs them, and sends an alert when something is really wrong. The checks cover the things that usually break a server: a file system that is nearly full, memory or CPU load that is too high, a program that has stopped, a network port that does not answer, and a web address that returns an error. What makes it a monitoring tool and not just a list of commands is the alert logic: it alerts once when a problem is confirmed, it stays silent while the problem continues, and it sends one more message when the problem is over.

Earlier lessons built the individual parts. Lesson 166 measured disk space, lesson 167 CPU and memory, lesson 168 websites with curl, lesson 172 a simple health-check script, and lesson 173 notifications. This project combines them and adds what makes alerts bearable for the people who receive them: a confirmation period and a memory of the previous results.

What the Script Should Do

  1. Read the checks from a file, one per line, with comments allowed.
  2. Run six kinds of checks: disk, mem, load, process, port and url.
  3. Remember the result of each check between runs, in a state directory.
  4. Confirm a problem before reporting it: a check must fail several runs in a row (-n, default 2) so that a short hiccup does not wake anybody up.
  5. Alert once per problem and once more when it recovers, through any program given with -a.
  6. Exit with status 1 while any check is failing, so other tools can use the result.

The Check File

A check file is plain text. Everything after # is a comment, and blank lines are ignored:

# what must be true on this server
disk /          90
mem             90
load            150
process sleep
port 127.0.0.1 8097
url  http://127.0.0.1:8097/
LineThe check fails when
disk / 90The file system mounted at / is more than 90% full
mem 90More than 90% of the memory is in use (without the cache that the system can release)
load 150The 1-minute load average is above 150% of the number of CPU cores
process sleepNo process has exactly the name sleep
port 127.0.0.1 8097A TCP connection to that address and port is refused or times out
url http://...The HTTP request fails or returns a status other than 2xx or 3xx

A load of 100% means that, on average, every core always has one process to run. Values above 100% mean that processes have to wait. A limit of 150% is a reasonable warning level for many servers, but the right value depends on the work the server does.

Design Decisions

One Function per Check

Every check is a small function that does two things: it sets the variable msg to a short description of the result, and it returns status 0 when the check passed and 1 when it failed. This is the pattern used for conditions in lesson 90:

check_disk() {
    local mount=$1 limit=$2 cap
    [[ -d $mount ]] || { msg="$mount does not exist"; return 1; }
    read -r _ _ _ _ cap _ < <(df -P -k -- "$mount" | tail -n +2)
    cap=${cap%\%}
    msg="$mount is ${cap}% full (limit ${limit}%)"
    (( cap <= limit ))
}

The last line is an arithmetic test, and its result becomes the return value of the function. The functions are always called directly and never inside $( ), because a command substitution runs in a subshell and the value of msg would be lost (the rule from lessons 93 and 197). The message is built in all cases, also when the check passes, so the report always shows the current value.

df -P prints the POSIX format with one line per file system, and read splits it into fields. The fifth field is the capacity, for example 29%, and the line cap=${cap%\%} removes the percent sign so that it can be used in arithmetic.

Checking a Port Without Extra Tools

Bash can open a network connection by itself. A redirection to the special path /dev/tcp/HOST/PORT creates a TCP connection:

timeout 3 bash -c 'exec 3<>"/dev/tcp/$0/$1"' 127.0.0.1 8097
echo $?

Expected output while a server listens on port 8097:

0

and 1 (connection refused) when nothing listens. The special file does not exist on the disk; Bash itself handles it. The details:

  • exec 3<>file opens the connection on file descriptor 3, for reading and writing. It succeeds only if the connection could be made.
  • The code runs in a small bash -c command so that a failing connection never ends the main script, and so that timeout 3 can stop it after three seconds if the destination does not answer at all (for example when a firewall silently drops the packets).
  • The host and port are given as the arguments $0 and $1 of the little script and are not pasted into the text of the command. If the check file ever contained something unusual, it could not be run as a command.

This is the check to use for services that do not speak HTTP, such as databases, mail servers and SSH.

Memory and Load Without Parsing Tool Output

The memory check reads /proc/meminfo and uses MemAvailable, the kernel's own estimate of memory that can be given to programs without swapping. Using MemFree instead would report a healthy server as full, because Linux fills spare memory with the file cache (lesson 197 explains this in detail).

The load check reads /proc/loadavg, removes the dot from the first value (0.09 becomes 009), and divides by the number of cores. The value 009 means nine hundredths of a load, which is also 9 percent of one core, so dividing by the core count gives a percentage without any decimal arithmetic. The prefix 10# forces base 10, so that 009 is not read as an invalid octal number:

pct=$(( 10#${load1/./} / cores ))

Remembering Results Between Runs

A health check runs again and again, typically from cron every minute or every five minutes. To know whether a failure is new or old, each check has a small state file in the state directory. It holds two numbers: how many runs in a row the check has failed, and whether an alert has already been sent for this problem.

key=${kind}_${arg1:-}_${arg2:-}
statefile=$statedir/${key//[^A-Za-z0-9._-]/_}
fails=0 alerted=0
[[ -r $statefile ]] && read -r fails alerted < "$statefile"

The check disk / 90 becomes the key disk_/_90. Characters that are unsafe in file names, such as / and :, are replaced by an underscore with a pattern substitution (${key//[^A-Za-z0-9._-]/_}). On the first run no state file exists, so the defaults of 0 and 0 apply.

The Alert Rules

The rules fit into a few lines, and they are the heart of the script:

if (( ok == 0 )); then
    if (( alerted )); then
        events+=("RECOVERED  $msg")
    fi
    fails=0 alerted=0
else
    fails=$((fails + 1))
    if (( fails >= runs && ! alerted )); then
        events+=("PROBLEM    $msg (failed $fails run(s) in a row)")
        alerted=1
    fi
fi
  • A passing check resets the counter. If an alert had been sent earlier, a RECOVERED event is added, and the person who received the problem report learns that it is over.
  • A failing check increases the counter. Only when the counter reaches the configured number and no alert has been sent yet does a PROBLEM event appear. After that, alerted stays 1, so the script is silent during the rest of the outage.

The result is exactly one message when a problem starts and one when it ends, no matter how long it lasts. Without this memory, a check every minute would send 60 mails an hour about the same full disk.

Reading the Check File on Its Own Descriptor

The main loop reads the check file line by line. Some of the commands inside the loop talk to the network or start other programs, and a program that reads standard input would take lines from the check file and make the loop end early, with no error message. The script therefore opens the file on its own file descriptor 8 and reads from there:

while read -r -u 8 kind arg1 arg2 _ || [[ -n ${kind:-} ]]; do
    ...
done 8< "$checkfile"

read -u 8 reads from descriptor 8, and done 8< file opens it for the loop. Standard input stays untouched. The condition || [[ -n ${kind:-} ]] makes sure that a last line without a newline at the end is still processed (lesson 114).

Delivering the Alert

The script does not know how to send mail, SMS or chat messages. It calls a program given with -a, passes the subject as the first argument and the message on standard input. Any program that follows this rule works, for example a small wrapper around mail, curl to a chat webhook (lesson 173), or just a script that appends to a file, as in the tests below. Without -a, the alert is printed, which is useful for tests and for cron (which mails any output to the owner of the job).

The Complete Script

#!/usr/bin/env bash
#
# healthcheck.sh - run the checks listed in a file and alert on confirmed problems
#
# Usage: healthcheck.sh [-s DIR] [-n RUNS] [-a COMMAND] [-q] CHECKFILE
#
# Options:
#   -s DIR      directory that remembers the result of earlier runs
#               (default: /var/tmp/healthcheck)
#   -n RUNS     a check must fail RUNS runs in a row before an alert is sent
#               (default: 2)
#   -a COMMAND  program that delivers an alert: it gets the subject as its first
#               argument and the message on standard input (default: print it)
#   -q          print nothing when everything is fine
#   -h          show this help
#
# CHECKFILE has one check per line ("#" starts a comment). A check fails when:
#   disk MOUNT PERCENT      file system fuller than PERCENT
#   mem PERCENT             memory in use above PERCENT
#   load PERCENT            1-minute load above PERCENT of the CPU cores
#   process NAME            no process with exactly this name
#   port HOST PORT          TCP connection refused or timed out
#   url URL                 HTTP request fails or returns an error status
#
# Exit status: 0 every check passed, 1 at least one check failed, 2 usage error.

set -euo pipefail
export LC_ALL=C

readonly PROG=${0##*/}

usage() { sed -n '3,29s/^# \{0,1\}//p' "$0"; }

die() {
    printf '%s: %s\n' "$PROG" "$1" >&2
    exit 2
}

statedir=/var/tmp/healthcheck runs=2 alert_cmd= quiet=0
while getopts ':s:n:a:qh' opt; do
    case $opt in
        s) statedir=$OPTARG ;;
        n) runs=$OPTARG ;;
        a) alert_cmd=$OPTARG ;;
        q) quiet=1 ;;
        h) usage; exit 0 ;;
        :) die "option -$OPTARG needs a value" ;;
        *) die "unknown option -$OPTARG (try -h)" ;;
    esac
done
shift $((OPTIND - 1))

[[ $runs =~ ^[1-9][0-9]*$ ]] || die "-n needs a whole number of at least 1"
(( $# == 1 )) || die "give exactly one check file (try -h)"
checkfile=$1
[[ -r $checkfile ]] || die "cannot read $checkfile"
[[ -z $alert_cmd ]] || command -v "${alert_cmd%% *}" >/dev/null || die "alert command not found: $alert_cmd"
mkdir -p "$statedir"

# --- the checks -----------------------------------------------------------------
# Each check sets $msg (a short explanation) and returns 0 when the check passed.
# They are called directly, never inside $( ), so that they can set variables.

check_disk() {
    local mount=$1 limit=$2 cap
    [[ -d $mount ]] || { msg="$mount does not exist"; return 1; }
    read -r _ _ _ _ cap _ < <(df -P -k -- "$mount" | tail -n +2)
    cap=${cap%\%}
    msg="$mount is ${cap}% full (limit ${limit}%)"
    (( cap <= limit ))
}

check_mem() {
    local limit=$1 key value unit total=0 avail=0 pct
    while read -r key value unit; do
        case $key in
            MemTotal:)     total=$value ;;
            MemAvailable:) avail=$value ;;
        esac
    done < /proc/meminfo
    (( total > 0 )) || { msg="cannot read /proc/meminfo"; return 1; }
    pct=$(( (total - avail) * 100 / total ))
    msg="memory in use is ${pct}% (limit ${limit}%)"
    (( pct <= limit ))
}

check_load() {
    local limit=$1 load1 cores pct
    read -r load1 _ < /proc/loadavg
    cores=$(nproc)
    pct=$(( 10#${load1/./} / cores ))        # hundredths of a load per core = percent
    msg="load is ${pct}% of $cores core(s) (limit ${limit}%)"
    (( pct <= limit ))
}

check_process() {
    if pgrep -x -- "$1" > /dev/null; then
        msg="process $1 is running"
    else
        msg="process $1 is NOT running"
        return 1
    fi
}

check_port() {
    if timeout 3 bash -c 'exec 3<>"/dev/tcp/$0/$1"' "$1" "$2" 2>/dev/null; then
        msg="$1:$2 accepts connections"
    else
        msg="$1:$2 does NOT accept connections"
        return 1
    fi
}

check_url() {
    local code
    code=$(curl -s -o /dev/null --max-time 5 -w '%{http_code}' -- "$1" || true)
    msg="$1 answered HTTP $code"
    [[ $code =~ ^[23] ]]
}

# --- run every check, remember the result, collect events ----------------------

events=()          # lines for the alert message
failing=0 total=0

while read -r -u 8 kind arg1 arg2 _ || [[ -n ${kind:-} ]]; do
    [[ -z ${kind:-} || $kind == \#* ]] && { kind=; continue; }
    total=$((total + 1))

    case $kind in
        disk)    [[ -n ${arg2:-} ]] || die "disk needs MOUNT and PERCENT"; ok=0; check_disk "$arg1" "$arg2" || ok=1 ;;
        mem)     [[ -n ${arg1:-} ]] || die "mem needs PERCENT";            ok=0; check_mem "$arg1" || ok=1 ;;
        load)    [[ -n ${arg1:-} ]] || die "load needs PERCENT";           ok=0; check_load "$arg1" || ok=1 ;;
        process) [[ -n ${arg1:-} ]] || die "process needs NAME";           ok=0; check_process "$arg1" || ok=1 ;;
        port)    [[ -n ${arg2:-} ]] || die "port needs HOST and PORT";     ok=0; check_port "$arg1" "$arg2" || ok=1 ;;
        url)     [[ -n ${arg1:-} ]] || die "url needs a URL";              ok=0; check_url "$arg1" || ok=1 ;;
        *)       die "unknown check '$kind' in $checkfile" ;;
    esac

    # one state file per check: "FAILS_IN_A_ROW ALERT_SENT"
    key=${kind}_${arg1:-}_${arg2:-}
    statefile=$statedir/${key//[^A-Za-z0-9._-]/_}
    fails=0 alerted=0
    [[ -r $statefile ]] && read -r fails alerted < "$statefile"

    if (( ok == 0 )); then
        status=" ok "
        if (( alerted )); then
            events+=("RECOVERED  $msg")
        fi
        fails=0 alerted=0
    else
        failing=$((failing + 1))
        fails=$((fails + 1))
        status="FAIL"
        if (( fails >= runs && ! alerted )); then
            events+=("PROBLEM    $msg (failed $fails run(s) in a row)")
            alerted=1
        fi
    fi
    echo "$fails $alerted" > "$statefile"

    (( quiet && ok == 0 )) || printf '[%s] %-10s %s\n' "$status" "$kind" "$msg"
    kind=
done 8< "$checkfile"      # a separate file descriptor: commands in the loop cannot steal these lines

(( total > 0 )) || die "$checkfile contains no checks"

# --- deliver the alert -----------------------------------------------------------

if (( ${#events[@]} > 0 )); then
    subject="Health check on $(hostname): ${#events[@]} change(s)"
    body=$(printf 'Host: %s\nTime: %s\n\n' "$(hostname)" "$(date '+%Y-%m-%d %H:%M:%S')"
           printf '%s\n' "${events[@]}")
    if [[ -n $alert_cmd ]]; then
        # shellcheck disable=SC2086   # the command may contain its own arguments
        printf '%s\n' "$body" | $alert_cmd "$subject"
    else
        printf '\n%s\n%s\n' "$subject" "$body"
    fi
fi

(( failing == 0 ))

Running the Health Check

The tests use a small web server on port 8097 (python3 -m http.server 8097 --bind 127.0.0.1) and a sleep process as the monitored program. The alert program notify.sh appends everything it receives to alerts.log:

#!/usr/bin/env bash
# test alert program: append the subject and the message to alerts.log
{ echo "=== ALERT: $1"; cat; echo; } >> "$(dirname "$0")/alerts.log"

Run 1: Everything Is Fine

$ ./healthcheck.sh -s st checks.conf; echo "status $?"
[ ok ] disk       / is 29% full (limit 90%)
[ ok ] mem        memory in use is 6% (limit 90%)
[ ok ] load       load is 0% of 2 core(s) (limit 150%)
[ ok ] process    process sleep is running
[ ok ] port       127.0.0.1:8097 accepts connections
[ ok ] url        http://127.0.0.1:8097/ answered HTTP 200
status 0

The option -s st puts the state files in the directory st. Every check shows the current value, not only the word "ok", so the log of a successful run is also useful.

Run 2: The Web Server Stops (First Failure)

$ ./healthcheck.sh -s st -a ./notify.sh checks.conf; echo "status $?"
[ ok ] disk       / is 29% full (limit 90%)
[ ok ] mem        memory in use is 6% (limit 90%)
[ ok ] load       load is 0% of 2 core(s) (limit 150%)
[ ok ] process    process sleep is running
[FAIL] port       127.0.0.1:8097 does NOT accept connections
[FAIL] url        http://127.0.0.1:8097/ answered HTTP 000
status 1

Two checks fail and the exit status is 1, but no alert is sent yet: alerts.log does not exist. The default confirmation period is two runs, and this is the first failure. A restart that takes a few seconds, or one lost packet, would never be reported.

Run 3: The Problem Is Confirmed

$ ./healthcheck.sh -s st -a ./notify.sh checks.conf; echo "status $?"
[ ok ] disk       / is 29% full (limit 90%)
...
[FAIL] port       127.0.0.1:8097 does NOT accept connections
[FAIL] url        http://127.0.0.1:8097/ answered HTTP 000
status 1
$ cat alerts.log
=== ALERT: Health check on vm: 2 change(s)
Host: vm
Time: 2026-12-02 17:44:44

PROBLEM    127.0.0.1:8097 does NOT accept connections (failed 2 run(s) in a row)
PROBLEM    http://127.0.0.1:8097/ answered HTTP 000 (failed 2 run(s) in a row)

The second failure confirms the problem. One message reports both failed checks together, so a single incident does not lead to a flood of separate messages.

Run 4: Still Failing

A fourth run, with the server still down, prints the same [FAIL] lines, but the alert log still contains exactly one alert (grep -c ALERT alerts.log prints 1). The state file of the port check shows the reason:

$ cat st/port_127.0.0.1_8097
3 1

Three failed runs in a row, and the alert has already been sent. The script stays silent until something changes.

Run 5: Recovery

After the server is started again:

$ ./healthcheck.sh -q -s st -a ./notify.sh checks.conf; echo "status $?"
status 0
$ tail -6 alerts.log
Host: vm
Time: 2026-12-02 17:44:51

RECOVERED  127.0.0.1:8097 accepts connections
RECOVERED  http://127.0.0.1:8097/ answered HTTP 200

With -q the passing checks are not printed, so the run produced no output at all, but the recovery message was delivered through the alert program. The next quiet run is silent, because no state has changed.

Printing the Alert and Stricter Settings

Without -a, the alert goes to standard output. With -n 1, an alert is sent at the first failure. The test file uses a limit that cannot be met and a program that does not exist:

$ printf 'disk / 10\nprocess no-such-daemon\n' > bad.conf
$ ./healthcheck.sh -n 1 -s st2 bad.conf; echo "status $?"
[FAIL] disk       / is 29% full (limit 10%)
[FAIL] process    process no-such-daemon is NOT running

Health check on vm: 2 change(s)
Host: vm
Time: 2026-12-02 17:44:51

PROBLEM    / is 29% full (limit 10%) (failed 1 run(s) in a row)
PROBLEM    process no-such-daemon is NOT running (failed 1 run(s) in a row)
status 1

Input Errors

$ ./healthcheck.sh
healthcheck.sh: give exactly one check file (try -h)
$ ./healthcheck.sh -n 0 x
healthcheck.sh: -n needs a whole number of at least 1
$ ./healthcheck.sh nofile
healthcheck.sh: cannot read nofile
$ printf 'cpu 5\n' > e.conf; ./healthcheck.sh -s st3 e.conf
healthcheck.sh: unknown check 'cpu' in e.conf
$ printf '# only comments\n' > e2.conf; ./healthcheck.sh -s st3 e2.conf
healthcheck.sh: e2.conf contains no checks
$ ./healthcheck.sh -a nonexist checks.conf
healthcheck.sh: alert command not found: nonexist

All of these exit with status 2. A check file with no checks is an error on purpose: a monitor that silently checks nothing looks the same as a healthy server.

Scheduling the Health Check

Run it every minute from cron (lesson 170), with the alert delivered by your notification script (lesson 173). The state directory must be writable by the user who runs the job and should survive between runs, which is why the default is /var/tmp and not /tmp:

* * * * * /usr/local/bin/healthcheck.sh -q -n 3 -a "/usr/local/bin/notify.sh" /etc/healthcheck/checks.conf

With a one-minute interval and -n 3, a problem is reported when it has lasted at least three minutes. For the check of a critical service, use a smaller number. For the file system and the load, which change slowly, a larger number reduces noise. To prevent two runs from overlapping on a slow system, combine the job with a lock (lesson 171):

* * * * * flock -n /var/lock/healthcheck.lock /usr/local/bin/healthcheck.sh -q -a /usr/local/bin/notify.sh /etc/healthcheck/checks.conf

Ideas for Extending the Project

  • Alert levels. Add a second, higher limit for each check, for example "warning at 80%, critical at 95%", and include the level in the message.
  • Reminders. Store the time of the alert in the state file and send a reminder every few hours while the problem continues.
  • Certificate expiry. Add a cert HOST DAYS check that uses openssl s_client and openssl x509 -enddate to warn before a TLS certificate runs out.
  • Service managers. Add a service NAME check based on systemctl is-active --quiet NAME for systems that run systemd.
  • Machine-readable output. Add a -o json mode, so that a dashboard can show the latest state of all checks.

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 Build a Server Health-Check and Alert Script and get answers drawn from it.

Signed-in readers only.