Using Bash to Process Application Logs
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:
| Field | Contains | Example |
|---|---|---|
$1 | client IP address | 203.0.113.120 |
$4 | [ followed by date and time | [30/Nov/2026:14:00:01 |
$6 | " followed by the HTTP method | "GET |
$7 | requested path | /static/app.js |
$9 | status code | 200 |
$10 | response size in bytes | 3203 |
$NF | response 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:
awk '{ print $9 }'reduces every line to the value being counted, here the status code.sortputs equal values next to each other. This step is required, becauseuniqonly merges adjacent duplicate lines.uniq -creplaces each group of equal lines with one line, prefixed by the number of lines in the group.sort -rnsorts 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