Using Bash to Process Application Logs

Su Suriya Ravichandran Updated 06 Dec 2026
27 min read ·Lesson 181 of 205

Applications and web servers write a line to a log file for every request they handle and every problem they meet. When something goes wrong, those files hold the answer to the first questions anyone asks: how many requests failed, since when, on which pages, for which users, and how slow everything was. Log files are plain text, one event per line, which is exactly the kind of data that Bash and the standard command-line tools process well. A pipeline of grep, awk, sort and uniq reads millions of lines in seconds, directly on the server, without installing anything.

This lesson shows how to take a log line apart into fields, count and rank events, group them by time, measure response times, read rotated and compressed files, handle JSON logs with jq, and watch a log as it grows. It ends with a reusable report script that combines these techniques.

The Structure of a Log Line

Before any command can count something in a log, you need to know where each piece of information sits in a line. The examples in this lesson use a web server access log in the combined log format, the default format of nginx and a common format for Apache, with the request duration added as the last field:

203.0.113.120 - - [30/Nov/2026:14:00:01 +0000] "GET /static/app.js HTTP/1.1" 200 3203 "-" "Mozilla/5.0 (X11; Linux x86_64)" 0.04

From left to right, the line contains the client's IP address, two fields that are usually - (the identity and the authenticated user), the time in square brackets, the request line in quotes (method, path and protocol), the HTTP status code, the size of the response in bytes, the referring page, the browser's user agent, and the time the server needed to answer, in seconds. In nginx, the duration comes from adding the $request_time variable to the log_format.

awk splits each line into fields at runs of spaces and tabs and numbers them $1, $2 and so on. A short loop shows exactly which number each part gets:

head -n 1 access.log | awk '{ for (i = 1; i <= NF; i++) printf "$%d=%s\n", i, $i }'
$1=203.0.113.120
$2=-
$3=-
$4=[30/Nov/2026:14:00:01
$5=+0000]
$6="GET
$7=/static/app.js
$8=HTTP/1.1"
$9=200
$10=3203
$11="-"
$12="Mozilla/5.0
$13=(X11;
$14=Linux
$15=x86_64)"
$16=0.04

NF is the number of fields in the current line, so the loop prints every field with its number. The useful ones are:

FieldContainsExample
$1client IP address203.0.113.120
$4[ followed by date and time[30/Nov/2026:14:00:01
$6" followed by the HTTP method"GET
$7requested path/static/app.js
$9status code200
$10response size in bytes3203
$NFresponse time in seconds (last field)0.04

Two details matter. First, awk does not understand quotes: the user agent "Mozilla/5.0 (X11; Linux x86_64)" became four fields, and other browsers produce more or fewer. Everything after the user agent therefore has no fixed field number, which is why the response time is read as $NF, the last field, counted from the end. Fields before the request line are stable because IP addresses, dates and status codes never contain spaces. Second, some fields carry punctuation from the format, such as the [ before the date and the " before the method. They are removed with substr or sub when needed, as shown below.

Application logs written by your own code usually have a simpler layout, such as 2026-11-30 14:41:12 ERROR payment gateway timeout, and the same approach applies: print the fields once, note their numbers, then build commands on them.

Finding and Counting Lines

The simplest questions are answered by counting lines. wc -l counts all lines, and grep -c counts the lines that contain a pattern:

wc -l < access.log
grep -c '" 404 ' access.log
600
54

The pattern '" 404 ' includes the closing quote of the request line and the spaces around the status, so it matches the status field and not a response size or a path that happens to contain 404. Patterns like this work, but they depend on the exact text around the value. When a condition is about a specific field, awk is more reliable, because it compares the field itself:

awk '$9 >= 500' access.log | head -n 3
198.51.100.3 - - [30/Nov/2026:14:13:20 +0000] "GET /products HTTP/1.1" 500 94 "-" "Mozilla/5.0 (X11; Linux x86_64)" 0.373
203.0.113.5 - - [30/Nov/2026:14:20:35 +0000] "GET /products HTTP/1.1" 500 99 "-" "Mozilla/5.0 (X11; Linux x86_64)" 0.294
203.0.113.88 - - [30/Nov/2026:14:33:48 +0000] "GET /static/app.js HTTP/1.1" 500 399 "-" "Mozilla/5.0 (X11; Linux x86_64)" 0.305

An awk program consists of condition { action } pairs. When the action is missing, awk prints the matching line, so $9 >= 500 alone prints every request that ended with a server error (status 500 to 599). Because $9 looks like a number, awk compares it numerically.

Ranking with sort and uniq

Most log questions have the form "which X occurs most often": which status codes, which pages, which clients. One pipeline answers all of them:

awk '{ print $9 }' access.log | sort | uniq -c | sort -rn
    454 200
     56 304
     54 404
     24 301
      9 500
      3 502

The pipeline works in four steps:

  1. awk '{ print $9 }' reduces every line to the value being counted, here the status code.
  2. sort puts equal values next to each other. This step is required, because uniq only merges adjacent duplicate lines.
  3. uniq -c replaces each group of equal lines with one line, prefixed by the number of lines in the group.
  4. sort -rn sorts by that number, numerically (-n) and in reverse order (-r), so the most frequent value comes first.

Changing the first step changes the question. A condition in front of the print narrows it down. These commands list the paths that most often returned "404 Not Found" and the five busiest clients:

awk '$9 == 404 { print $7 }' access.log | sort | uniq -c | sort -rn | head -n 5
awk '{ print $1 }' access.log | sort | uniq -c | sort -rn | head -n 5
     10 /phpmyadmin/
     10 /.env
      9 /admin.php
      8 /wp-login.php
      5 /api/orders
    112 203.0.113.88
    100 198.51.100.3
     97 203.0.113.5
     91 203.0.113.120
     86 203.0.113.17

The 404 list is typical for any server reachable from the internet: /phpmyadmin/, /.env, /admin.php and /wp-login.php do not exist on this site. They are requested by automated scanners that look for exposed admin tools and configuration files. The next section finds out where they come from.

Counting per Key with awk Arrays

The sort | uniq -c pipeline counts one thing at a time. When a question combines several values, such as "how many 404 responses did each client get, and who got many", awk's associative arrays do the counting in one pass. An associative array maps keys to values, like a dictionary in other languages; using an element that does not exist yet creates it with an empty value, which counts as 0:

awk '$9 == 404 { c[$1]++ }
     END { for (ip in c) if (c[ip] >= 10) print c[ip], ip }' access.log | sort -rn
37 198.51.100.9

For every 404 response, c[$1]++ increases the counter for that client's IP address. The END block runs once after the last line has been read. It loops over all keys of the array and prints the clients with at least 10 such responses. A single client asked for 37 pages that do not exist, which identifies it as the scanner. This is the kind of result you would feed into a firewall rule or a tool like fail2ban.

Arrays can hold sums and maximums as well as counts. This command computes the number of requests, the average and the maximum response time for every path:

awk '{ n[$7]++; sum[$7] += $NF; if ($NF > max[$7]) max[$7] = $NF }
     END { for (p in n) printf "%-16s %4d %8.3f %8.3f\n", p, n[p], sum[p] / n[p], max[p] }' access.log |
    sort -k3,3nr | head -n 5
/api/orders        81    1.483    2.746
/checkout          70    0.228    0.398
/login             61    0.222    0.398
/products          90    0.205    0.387
/                  61    0.199    0.399

Three arrays share the same key, the path: n counts requests, sum adds up their durations, and max remembers the longest one. printf formats the output into aligned columns; %-16s prints a string left-aligned in 16 characters and %8.3f a number with three decimals in 8 characters. Because awk visits array keys in no particular order, the output is sorted afterwards: sort -k3,3nr sorts by the third column only, numerically and in reverse. The API endpoint /api/orders stands out with an average of 1.5 seconds, about seven times slower than every other page.

Percentiles: Beyond the Average

An average hides how bad the slow requests are. Engineers therefore look at percentiles: the 95th percentile (p95) is the duration that 95 % of requests stay below, so it describes what the slowest one in twenty users experiences. Calculating it requires the values in sorted order:

awk '$7 == "/api/orders" { print $NF }' access.log | sort -n |
    awk '{ v[NR] = $1 }
         END {
             i = int(NR * 0.95); if (i < NR * 0.95) i++
             printf "count=%d p50=%s p95=%s max=%s\n", NR, v[int((NR + 1) / 2)], v[i], v[NR]
         }'
count=81 p50=1.51 p95=2.675 max=2.746

The first awk extracts the durations of one endpoint, and sort -n orders them from fastest to slowest. The second awk stores the sorted values in an array indexed by line number (NR). At the end, the p95 value is the element at position 95 % of the count, rounded up, which is the "nearest rank" method; the median (p50) sits in the middle and the maximum at the end. Half of the order requests took more than 1.5 seconds, and one in twenty took more than 2.6 seconds.

Working with Time

Logs are timelines, and many questions are about time: when did the errors start, and when did they stop? The timestamp field [30/Nov/2026:14:00:01 has a fixed width, so substr can cut pieces out of it by position. awk counts string positions from 1: the hour starts at position 14, so substr($4, 14, 5) returns 14:00, the hour and minute.

Grouping requests into ten-minute periods only needs the first digit of the minutes: substr($4, 14, 4) returns 14:0, 14:1 and so on, and appending a 0 turns that into a readable label. The following command counts requests and server errors per ten minutes and calculates the error rate:

awk '{ bucket = substr($4, 14, 4) "0"; total[bucket]++; if ($9 >= 500) err[bucket]++ }
     END { for (b in total) printf "%s %4d req %3d 5xx %5.1f%%\n", b, total[b], err[b], 100 * err[b] / total[b] }' access.log |
    sort
14:00   50 req   0 5xx   0.0%
14:10   58 req   1 5xx   1.7%
14:20   54 req   1 5xx   1.9%
14:30   46 req   1 5xx   2.2%
14:40   49 req   6 5xx  12.2%
14:50   44 req   0 5xx   0.0%
15:00   60 req   0 5xx   0.0%
15:10   61 req   0 5xx   0.0%
15:20   42 req   2 5xx   4.8%
15:30   44 req   0 5xx   0.0%
15:40   45 req   1 5xx   2.2%
15:50   47 req   0 5xx   0.0%

Placing two strings side by side in awk concatenates them, so substr($4, 14, 4) "0" produces the label. err[b] is empty for periods without errors, and an empty value counts as 0 in a calculation, so the error rate comes out as 0.0% without special handling. The table shows a clear incident between 14:40 and 14:50, when the error rate jumped from about 2 % to over 12 %.

To look inside that period, filter by time. Strings in the form HH:MM sort in the same order as the times they represent, so plain string comparison selects a time window:

awk -v from=14:40 -v to=14:50 '
    { t = substr($4, 14, 5) }
    t >= from && t < to && $9 >= 500 { print t, $9, $6, $7 }' access.log | tr -d '"'
14:42 502 POST /checkout
14:43 502 POST /checkout
14:46 500 POST /checkout
14:47 500 POST /checkout
14:48 500 GET /login
14:49 502 POST /checkout

-v from=14:40 passes a value from the shell into an awk variable; this is the safe way to give awk a value, because it is never interpreted as program code (lesson 155 explains why building programs from strings is dangerous). The first block computes the time of every line, and the second prints the server errors inside the window. tr -d '"' deletes the quote that the method field carries. Five of the six errors were checkout requests, so the problem was in the checkout process, most likely the payment service it depends on.

The comparison of HH:MM strings only works within one day. For windows that cross midnight or span several days, compare a sortable form of the complete timestamp, such as 2026-11-30T14:40, which ISO 8601 timestamps in application logs already are.

Rotated and Compressed Logs

Log files are rotated so they do not grow forever: a tool such as logrotate periodically renames access.log to access.log.1, starts a new empty file, and compresses older files to access.log.2.gz and so on (lesson 165 builds a rotation script). Questions about yesterday or last week therefore involve several files, some of them compressed.

zcat decompresses gzip files to standard output. With the -f (force) option, it also passes through files that are not compressed, so one command reads a mixture of both, in the order given:

zcat -f access.log.1.gz access.log | wc -l
zcat -f access.log.1.gz access.log |
    awk '{ split($4, d, ":"); day = substr(d[1], 2); total[day]++; if ($9 >= 500) e[day]++ }
         END { for (k in total) printf "%s %d requests, %d server errors\n", k, total[k], e[k] }' | sort
1100
29/Nov/2026 500 requests, 6 server errors
30/Nov/2026 600 requests, 12 server errors

split($4, d, ":") cuts the timestamp field at every colon into the array d; d[1] is [30/Nov/2026, and substr(d[1], 2) removes the bracket. Note that sort sorts these dates as text, which happens to be correct here but would put 01/Dec before 30/Nov; for longer ranges, convert dates to a sortable form first.

Most search tools have compressed counterparts: zgrep works like grep on compressed and plain files, and zless pages through them. Decompressing on the fly is fast and leaves the files on disk unchanged:

zgrep -c '/checkout' access.log.1.gz
58

JSON Logs with jq

Many modern applications write structured logs: one JSON object per line, sometimes called JSON Lines. Each event has named fields instead of positions, which removes the guesswork about field numbers:

{"ts":"2026-11-30T14:41:12Z","level":"ERROR","msg":"payment gateway timeout","request_id":"r0180"}

Splitting JSON with awk or cut is fragile, because field order can change and values can contain spaces, commas and quotes. The tool for this job is jq, a command-line JSON processor available as a package on all major distributions (apt install jq, dnf install jq, brew install jq). jq reads one JSON value after another, applies a filter to each, and prints the results. -r prints strings raw, without JSON quotes, so the output can flow into the usual text tools:

jq -r '.level' app.jsonl | sort | uniq -c | sort -rn
jq -r 'select(.level == "ERROR") | .msg' app.jsonl | sort | uniq -c | sort -rn
    169 INFO
     37 ERROR
     34 WARN
     23 payment gateway timeout
      9 database connection refused
      5 order validation failed

.level extracts a field. select(condition) passes on only the objects for which the condition is true, and the pipe | inside the jq program sends each selected object to the next filter, just like a shell pipe. The error messages confirm what the access log suggested: most errors were payment gateway timeouts.

jq can also format its output. @tsv turns an array into a line of tab-separated values, convenient for further processing with cut or awk, and string interpolation with 0 ) builds custom text. ISO 8601 timestamps compare correctly as strings, so time windows work with plain comparisons:

jq -r 'select(.level == "ERROR" and .ts >= "2026-11-30T14:40" and .ts < "2026-11-30T14:42")
       | [.ts, .request_id, .msg] | @tsv' app.jsonl
jq -r 'select(.duration_ms > 3500) | "\(.ts) \(.duration_ms)ms \(.request_id)"' app.jsonl
jq -r 'select(.level == "ERROR") | .ts[11:15] + "0"' app.jsonl | sort | uniq -c
2026-11-30T14:41:12Z	r0180	payment gateway timeout
2026-11-30T14:41:33Z	r0181	payment gateway timeout
2026-11-30T14:20:47Z 3686ms r0082
2026-11-30T14:37:05Z 3922ms r0168
      3 14:00
      3 14:10
      3 14:20
      5 14:30
     19 14:40
      4 14:50

The second command selects only events that have a duration_ms field above 3500: for events without the field, .duration_ms is null, and jq treats null as smaller than any number, so they are skipped without an error. In the third command, .ts[11:15] slices characters 11 to 14 out of the timestamp (jq counts from 0), giving 14:4, and + "0" completes the ten-minute label. The application log shows the same spike between 14:40 and 14:50 as the access log, with 19 errors.

The request_id field is what connects these two views of the same incident: when the application also passes the ID to the web server or includes it in its responses, a single grep r0180 across all logs collects every line about one request.

One damaged line, such as a line cut off when the disk filled up, stops jq with a parse error, and the events after it are lost:

printf '%s\n' '{"level":"INFO","msg":"ok"}' 'not json' '{"level":"ERROR","msg":"x"}' > mixed.jsonl
jq -r '.level' mixed.jsonl; echo "status $?"
jq -R -r 'fromjson? | .level' mixed.jsonl; echo "status $?"
INFO
jq: parse error: Invalid numeric literal at line 2, column 4
status 5
INFO
ERROR
status 0

With -R, jq reads each line as a raw string instead of parsing it. fromjson then parses the string, and the ? suppresses the error for lines that are not valid JSON, so they are skipped and the rest is processed.

Following a Live Log

The commands so far analyze what already happened. During an incident or after a deployment, you often want to watch events as they arrive. tail -f prints new lines as they are written to a file. Its sibling tail -F (capital F) is better for logs: it also notices when the file is rotated, reopens the new file under the same name, and keeps following it. -n 0 skips the existing lines, so only new events are processed.

Each line can be handled by a while read loop. The script below counts server errors per minute and prints an alert when one minute reaches a threshold:

#!/usr/bin/env bash
#
# watch-5xx.sh - follow an access log and alert when one minute has too many 5xx responses
#
# Usage: watch-5xx.sh LOGFILE [THRESHOLD]   (THRESHOLD defaults to 5)

set -euo pipefail

log=${1:?usage: watch-5xx.sh LOGFILE [THRESHOLD]}
threshold=${2:-5}
minute='' count=0 alerted=''

tail -F -n 0 -- "$log" 2> /dev/null |
while read -r ip _ _ ts _ _ _ _ status _; do
    [[ $status == 5?? ]] || continue          # only server errors
    m=${ts:13:5}                               # "[30/Nov/2026:14:42:10" -> "14:42"
    if [[ $m != "$minute" ]]; then             # a new minute starts a new count
        minute=$m count=0 alerted=''
    fi
    (( ++count ))
    if (( count >= threshold )) && [[ -z $alerted ]]; then
        printf '%(%T)T ALERT: %d server errors in minute %s (latest from %s)\n' \
            -1 "$count" "$minute" "$ip"
        alerted=yes                            # one alert per minute is enough
    fi
done

read splits each line into words at spaces, the same way awk splits fields, and assigns them to the listed variables in order. The underscore _ is a conventional name for values that are not needed. The last variable, also _, receives the whole rest of the line, so the varying number of words in the user agent does not matter. The positions match the awk field numbers from the start of this lesson: ip receives field 1, ts field 4 and status field 9.

[[ $status == 5?? ]] is a pattern match: 5?? matches any three-character value that starts with 5. ${ts:13:5} extracts five characters starting at position 13; Bash counts positions from 0, so this is the same text as awk's substr($4, 14, 5). When a line belongs to a new minute, the counter starts over. The alerted flag ensures that a burst of fifty errors produces one alert, not fifty. printf '%(%T)T' prints the current time without starting a date process.

To test the script, run it with a low threshold and append lines to the log from another terminal. The test below also renames the log in the middle, the way logrotate does:

./watch-5xx.sh live.log 2
05:45:19 ALERT: 2 server errors in minute 09:20 (latest from 203.0.113.5)

One error was written before the rename and one after it, into the new live.log. Because tail -F reopened the new file, both were counted in the same minute and the alert fired. With tail -f, the script would have kept reading the renamed old file and missed the second error. In a real setup, the printf would be replaced by a call to a notification function (lesson 173), and the script would run as a service.

When awk is used inside such a live pipeline instead of read, be aware of output buffering. When awk's output goes to a pipe or file rather than a terminal, it collects output in a buffer and writes it in large blocks, so alerts can appear minutes late. Calling fflush() after each print forces the output out immediately. mawk, the default awk on Debian and Ubuntu, additionally buffers its input; start it with mawk -W interactive in live pipelines. For grep in the middle of a live pipeline, the equivalent option is --line-buffered.

A Complete Example: A Reusable Log Report

The commands in this lesson are useful on their own, but during an incident nobody wants to retype them. log-report.sh collects the most important ones into a single report. It reads any number of plain or compressed log files, optionally limits the analysis to a time window, and prints the status code distribution, the periods and paths with the most server errors, the slowest paths, the busiest clients and possible scanners.

#!/usr/bin/env bash
#
# log-report.sh - summarize web server access logs
#
# Usage: log-report.sh [-f HH:MM] [-t HH:MM] [-n N] LOGFILE...
#   -f HH:MM   only requests at or after this time of day (default 00:00)
#   -t HH:MM   only requests before this time of day (default 24:00)
#   -n N       number of entries in each list (default 5)
# Plain and gzip-compressed files can be mixed: access.log access.log.1.gz
#
# Expected format: combined log format with the response time in seconds
# as the last field (nginx: $request_time, Apache: %{ms}T divided by 1000).

set -euo pipefail

usage() { sed -n '5,9s/^# \{0,1\}//p' "$0" >&2; exit 2; }
die()   { echo "${0##*/}: $*" >&2; exit 2; }

from=00:00 to=24:00 top=5
while getopts ':f:t:n:h' opt; do
    case $opt in
        f) from=$OPTARG ;;
        t) to=$OPTARG ;;
        n) top=$OPTARG ;;
        *) usage ;;
    esac
done
shift $(( OPTIND - 1 ))
(( $# >= 1 )) || usage
[[ $from =~ ^[0-2][0-9]:[0-5][0-9]$ ]] || die "-f needs HH:MM, got '$from'"
[[ $to =~ ^[0-2][0-9]:[0-5][0-9]$ ]]   || die "-t needs HH:MM, got '$to'"
[[ $top =~ ^[1-9][0-9]*$ ]]            || die "-n needs a positive number, got '$top'"
for f in "$@"; do [[ -f $f && -r $f ]] || die "cannot read $f"; done

work=$(mktemp)
trap 'rm -f -- "$work"' EXIT

# Pass 1: read every file once, skip malformed lines, keep the time window,
# and reduce each request to six fields: date time status method path seconds client
zcat -f -- "$@" | awk -v from="$from" -v to="$to" '
    NF < 12 || $9 !~ /^[0-9][0-9][0-9]$/ { bad++; next }
    { t = substr($4, 14, 5) }
    t >= from && t < to {
        method = $6; sub(/^"/, "", method)
        print substr($4, 2, 11), t, $9, method, $7, $NF, $1
    }
    END { if (bad) printf "note: skipped %d malformed lines\n", bad > "/dev/stderr" }
' > "$work"

total=$(wc -l < "$work")
if (( total == 0 )); then
    echo "No requests between $from and $to."
    exit 0
fi

# first N lines; unlike head, it reads all input, so the writer never gets SIGPIPE
first() { awk -v n="$top" 'NR <= n'; }
section() { printf '\n== %s ==\n' "$1"; }

printf 'Requests from %s to %s in %d file(s): %d\n' "$from" "$to" "$#" "$total"

section 'Responses by status class'
awk -v total="$total" '{ c[substr($3, 1, 1) "xx"]++ }
    END { for (k in c) printf "%s %7d %6.1f%%\n", k, c[k], 100 * c[k] / total }' "$work" | sort

section 'Ten-minute periods with the most 5xx responses'
awk '$3 >= 500 { print $1, substr($2, 1, 4) "0" }' "$work" | sort | uniq -c | sort -rn | first

section 'Paths with the most 5xx responses'
awk '$3 >= 500 { print $5 }' "$work" | sort | uniq -c | sort -rn | first

section 'Slowest paths (average and maximum seconds, requests)'
awk '{ n[$5]++; sum[$5] += $6; if ($6 > max[$5]) max[$5] = $6 }
    END { for (p in n) printf "%7.3f %7.3f %6d  %s\n", sum[p] / n[p], max[p], n[p], p }' "$work" |
    sort -rn | first

section 'Busiest clients'
awk '{ print $7 }' "$work" | sort | uniq -c | sort -rn | first

section 'Clients with 10 or more 404 responses (possible scanners)'
awk '$3 == 404 { c[$7]++ } END { for (ip in c) if (c[ip] >= 10) printf "%7d %s\n", c[ip], ip }' "$work" |
    sort -rn | first

How It Works

  • Options and validation. getopts (lesson 130) parses -f, -t and -n. Each value is checked with a regular expression before it is used, and each log file must exist and be readable. Invalid input stops the script with exit status 2 and a clear message.
  • One pass over the raw logs. Large logs are read only once. zcat -f streams all files, plain or compressed, into a single awk program that does three things: it skips malformed lines, it applies the time window, and it reduces each remaining request to seven clean fields (date, time, status, method, path, seconds, client) in a temporary file. All later sections work on this small, well-formed file, so they need no knowledge of the log format: field $3 is always the status and $6 always the duration.
  • Malformed lines. Real logs contain broken lines: a line cut off when a server crashed, or a message from another program written to the same file. A line with fewer than 12 fields or a status that is not three digits is counted and skipped instead of producing nonsense such as an empty path with a huge error count. The note goes to standard error, so it does not mix with the report.
  • Temporary file cleanup. mktemp creates a unique file, and the EXIT trap removes it however the script ends (lesson 124).
  • The empty case. A time window without requests is not an error. The script says so and exits with status 0 instead of printing empty sections or dividing by zero.

Why the Script Uses first Instead of head

With set -o pipefail, a pipeline fails if any command in it fails. head -n 5 exits as soon as it has printed five lines. If the command before it still has more output to write, that command is killed by the signal SIGPIPE and the pipeline reports status 141, which set -e turns into a silent abort of the whole script. With small outputs, this rarely happens, because everything fits into the pipe's buffer before head exits; with a large log, such as one with a hundred thousand different client addresses, it happens every time. The difference is easy to see:

set -o pipefail
seq 1 200000 | sort -rn | head -n 3; echo "status $?"
seq 1 200000 | sort -rn | awk 'NR <= 3'; echo "status $?"
200000
199999
199998
status 141
200000
199999
199998
status 0

The first function prints the same lines as head but keeps reading until the end of the input, so the command before it always finishes normally.

Running the Complete Example

Run against the current log, the report shows the whole day at a glance:

$ ./log-report.sh access.log
Requests from 00:00 to 24:00 in 1 file(s): 600

== Responses by status class ==
2xx     454   75.7%
3xx      80   13.3%
4xx      54    9.0%
5xx      12    2.0%

== Ten-minute periods with the most 5xx responses ==
      6 30/Nov/2026 14:40
      2 30/Nov/2026 15:20
      1 30/Nov/2026 15:40
      1 30/Nov/2026 14:30
      1 30/Nov/2026 14:20

== Paths with the most 5xx responses ==
      5 /checkout
      2 /products
      1 /static/app.js
      1 /products/42
      1 /login

== Slowest paths (average and maximum seconds, requests) ==
  1.483   2.746     81  /api/orders
  0.228   0.398     70  /checkout
  0.222   0.398     61  /login
  0.205   0.387     90  /products
  0.199   0.399     61  /

== Busiest clients ==
    112 203.0.113.88
    100 198.51.100.3
     97 203.0.113.5
     91 203.0.113.120
     86 203.0.113.17

== Clients with 10 or more 404 responses (possible scanners) ==
     37 198.51.100.9
[status 0]

Narrowing the window to the half hour around the incident, including yesterday's compressed log, reveals something new: the checkout failures between 14:40 and 14:50 happened on both days. A problem that recurs at the same time every day points to a scheduled job, such as a nightly batch at the payment provider or a backup on the database server, rather than to a random failure. The current log in this test also contains two damaged lines, which are reported and skipped:

$ ./log-report.sh -f 14:30 -t 15:00 -n 3 access.log.1.gz access.log
note: skipped 2 malformed lines
Requests from 14:30 to 15:00 in 2 file(s): 271

== Responses by status class ==
2xx     210   77.5%
3xx      29   10.7%
4xx      22    8.1%
5xx      10    3.7%

== Ten-minute periods with the most 5xx responses ==
      6 30/Nov/2026 14:40
      3 29/Nov/2026 14:40
      1 30/Nov/2026 14:30

== Paths with the most 5xx responses ==
      8 /checkout
      1 /static/app.js
      1 /login

== Slowest paths (average and maximum seconds, requests) ==
  1.629   2.693     28  /api/orders
  0.216   0.373     23  /
  0.214   0.390     34  /checkout

== Busiest clients ==
     65 203.0.113.88
     46 203.0.113.17
     42 203.0.113.42

== Clients with 10 or more 404 responses (possible scanners) ==
     14 198.51.100.9
[status 0]

Invalid input, an empty window and missing arguments are all handled:

$ ./log-report.sh -f 2pm access.log
log-report.sh: -f needs HH:MM, got '2pm'
[status 2]
$ ./log-report.sh -f 03:00 -t 04:00 access.log
No requests between 03:00 and 04:00.
[status 0]
$ ./log-report.sh missing.log
log-report.sh: cannot read missing.log
[status 2]
$ ./log-report.sh
Usage: log-report.sh [-f HH:MM] [-t HH:MM] [-n N] LOGFILE...
  -f HH:MM   only requests at or after this time of day (default 00:00)
  -t HH:MM   only requests before this time of day (default 24:00)
  -n N       number of entries in each list (default 5)
Plain and gzip-compressed files can be mixed: access.log access.log.1.gz
[status 2]

The awk programs in this lesson use only standard awk features, so they behave the same in gawk (GNU awk), mawk and the BSD awk on macOS; the examples were run with mawk 1.3.4 and Bash 5.2.

When Bash Is Not Enough

Command-line log processing is the fastest way to answer a question on one server about the last few days. It reaches its limits when logs are spread over many servers, when you need months of history, or when the same questions are asked every day. That is the job of centralized logging systems, such as the Elastic stack, Grafana Loki or a cloud provider's log service, which collect logs from all machines and index them for fast searching and dashboards. Even then, the techniques in this lesson remain useful, because those systems query the same fields, and an engineer who can count, group and filter log lines with a pipeline can quickly check what any dashboard shows. Lesson 195 builds on this lesson with a complete log file analyzer project.

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 Using Bash to Process Application Logs and get answers drawn from it.

Signed-in readers only.