Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 3

Answering questions from an access log with pipelines

Harness Unix standard streams, pipeline concurrency, and stream-processing utilities (grep, cut, awk, sort, uniq) to triage production incidents from server access logs.

Contentsand lesson path

What you will learn

  • Combine commands with pipes and redirection (grep, sort, uniq, cut, awk) to answer a specific question from a log file.

01. Standard Streams and Redirection Mechanics

When the Linux kernel spawns a process, it initializes three standard POSIX I/O file descriptors by default:

  • Standard Input (stdin, File Descriptor 0): Default data input stream, normally connected to the keyboard or fed from an upstream command via a pipe.
  • Standard Output (stdout, File Descriptor 1): Default stream for the normal results of a command, connected by default to the terminal screen.
  • Standard Error (stderr, File Descriptor 2): Unbuffered diagnostic stream intended for error notices, warnings, and tracebacks, emitted independently of standard output.

Bash controls stream routing using redirection operators evaluated strictly from left to right:

  • > : Truncates destination file and redirects standard output.
  • >> : Appends standard output to the end of the destination file without truncating existing content.
  • < : Reads standard input from a file instead of the interactive keyboard terminal.
  • 2> : Redirects standard error exclusively to a designated file or stream.
  • 2>&1 : Duplicates the current destination of standard output (fd 1) onto standard error (fd 2).
  • > /dev/null 2>&1 : Discards all output (both stdout and stderr) by sending it to /dev/null, a device that throws away whatever is written to it.

The ordering of redirection operators on the shell command line is critical and frequently misunderstood during incident automation. In the code snippet below, we observe how pointing standard output to a file before duplicating file descriptor 1 onto file descriptor 2 successfully consolidates both normal application output and error messages into a single log file.

Bash · Comparing stream redirection ordering patterns
# Correct: stdout goes to file, then stderr duplicates stdout destination
./rotate-certs.sh > rotate.log 2>&1

# Incorrect order: stderr duplicates current stdout (terminal), then stdout moves
# Errors still print to terminal display instead of the log file!
./rotate-certs.sh 2>&1 > rotate.log

# Modern Bash shortcut for redirecting both streams simultaneously
./rotate-certs.sh &> rotate.log

In the first example above, stdout (fd 1) is first pointed to rotate.log. Next, 2>&1 instructs the kernel to duplicate whatever fd 1 points to onto fd 2 (stderr), sending both streams into rotate.log. Conversely, writing ./rotate-certs.sh 2>&1 > rotate.log copies fd 1 (which still points to the terminal screen) onto fd 2, and then redirects fd 1 to the file. As a result, standard output enters the file, but errors continue to print on the terminal screen.

Understanding this left-to-right evaluation allows engineers to craft precise log capture rules for cron tasks, container entrypoints, and CI/CD automation runners.

02. Pipeline Architecture: Connecting Processes with Pipes

The Unix pipe operator connects the stdout of the command on the left directly to the stdin of the command on the right using a kernel memory circular ring buffer. Commands in a pipeline do not run sequentially; they execute concurrently in separate subshell processes. When the upstream producer writes faster than the consumer can process, the kernel blocks the producer until buffer space clears, providing automatic flow control without creating intermediate temporary files on disk.

The core utilities used in log processing pipelines include:

  • grep -E "pattern": Filters lines matching an extended regular expression. Use -v to invert matching, -i for case-insensitive search, and -c to count matching lines.
  • cut -d" " -f1: Extracts specific delimited fields from text columns (delimited by space in this example). Highly efficient for fixed single-character delimiters.
  • awk 'condition { action }': A full Turing-complete pattern scanning language for column processing. Field $1 represents the first column, $NF represents the last column, and $0 represents the whole line. It supports arithmetic comparisons, regular expression matching, and associative arrays.
  • sort: Sorts lines lexicographically by default. Add -n for numeric sorting, -r for reverse descending order, and -k2 to sort by the second column.
  • uniq -c: Prefixes each unique line with its occurrence count. uniq only merges duplicate lines that are next to each other, so unless equal lines are already grouped together, pipe the stream through sort first.
  • head -n 5 and tail -n 5: Keeps the first or last 5 lines of a stream (-n N for any other count).

When parsing web server logs, pick the tool that matches how the fields are separated. cut is small and fast, but it treats consecutive whitespace characters as separate empty delimiters. In contrast, awk treats arbitrary consecutive whitespace (spaces and tabs) as a single field delimiter by default. For log formats with variable spacing, awk copes without the extra tr -s " " step that cut would need to squeeze the spaces first.

03. Lab Exercise: Pinpointing Faulty IPs from an Access Log

During a production outage, an API gateway is returning HTTP 5xx errors. We need to identify the client IP addresses generating the largest volume of server errors from the Nginx Combined Log Format log file (access.log).

In standard Nginx combined logs, the fields are structured as follows:

  • Field 1 ($1): Client remote IP address.
  • Field 4 ($4): Timestamp and timezone offset.
  • Field 7 ($7): HTTP request URI.
  • Field 9 ($9): HTTP response status code (e.g. 200, 404, 500, 502, 503).
  • Field 10 ($10): Response body byte size transmitted.

These numbers assume a well-formed request line of exactly three words (method, path, protocol). Step 1 creates a small sample log so you can run every command yourself; in a real incident you would point the same commands at the server's log, for example /var/log/nginx/access.log.

  1. Create an empty working directory, cd into it and paste the block below. It writes a 12-line access.log and counts its lines.
  2. Run the triage pipeline: filter status codes starting with 5, extract the client IP, count, sort by frequency and show the top 5 sources.
  3. Check the parse: print field 9 of the malformed line, then count every status with a parse that splits on the double quote, and compare the two.
Bash · step 1, create the sample access.log
cat > access.log <<'EOF'
10.0.0.15 - - [27/Oct/2026:10:00:01 +0000] "GET /orders HTTP/1.1" 502 157 "-" "curl/8"
10.0.0.20 - - [27/Oct/2026:10:00:02 +0000] "GET / HTTP/1.1" 200 612 "-" "Edge"
10.0.0.15 - - [27/Oct/2026:10:00:03 +0000] "POST /orders HTTP/1.1" 503 0 "-" "curl/8"
172.16.0.88 - - [27/Oct/2026:10:00:04 +0000] "GET /stock HTTP/1.1" 500 89 "-" "python"
10.0.0.20 - - [27/Oct/2026:10:00:05 +0000] "GET /logo.png HTTP/1.1" 404 153 "-" "Edge"
10.0.0.15 - - [27/Oct/2026:10:00:06 +0000] "GET /orders HTTP/1.1" 502 157 "-" "curl/8"
10.0.0.66 - - [27/Oct/2026:10:00:07 +0000] "-" 400 0 "-" "-"
172.16.0.88 - - [27/Oct/2026:10:00:08 +0000] "GET /stock HTTP/1.1" 504 167 "-" "python"
10.0.0.21 - - [27/Oct/2026:10:00:09 +0000] "GET /health HTTP/1.1" 200 2 "-" "probe"
10.0.0.15 - - [27/Oct/2026:10:00:10 +0000] "GET /orders HTTP/1.1" 500 89 "-" "curl/8"
10.0.0.20 - - [27/Oct/2026:10:00:11 +0000] "GET /orders HTTP/1.1" 200 1043 "-" "Edge"
172.16.0.88 - - [27/Oct/2026:10:00:12 +0000] "GET /stock HTTP/1.1" 200 734 "-" "python"
EOF
wc -l access.log
Expected output
12 access.log
Bash · step 2, the triage pipeline
# Filter for HTTP 5xx errors, count by client IP, and show top 5
awk '$9 ~ /^5/ { print $1 }' access.log | sort | uniq -c | sort -rn | head -n 5
Expected output
      4 10.0.0.15
      2 172.16.0.88

The output reveals that client 10.0.0.15 generated 4 distinct 5xx errors, while 172.16.0.88 generated 2 errors. We can then isolate the requests from 10.0.0.15 with awk '$1 == "10.0.0.15"' access.log to see the exact endpoints and timestamps behind the errors (here: /orders, four times in ten seconds).

The same pipeline works on a real server log of many megabytes, and it gives you an answer from the host itself while a central log system (such as Elasticsearch or Datadog) may still be ingesting the latest lines. On very large files, filter early (awk or grep first) so that sort has less to do.

Whitespace field numbers break when a request line is not three words. Line 7 of the sample comes from a client that sent garbage, which nginx logs as "-". On that line $9 is not the status at all:

Bash · step 3, field shift on a malformed request, and a sturdier parse
awk '$1 == "10.0.0.66" { print $9 }' access.log
# Split on the double quote instead: field 3 is ' <status> <bytes> '
awk -F'"' '{ split($3, a, " "); print a[1] }' access.log | sort | uniq -c
Expected output
"-"
      4 200
      1 400
      1 404
      2 500
      2 502
      1 503
      1 504

The first command prints "-", so a filter on $9 silently skips that line. Here it was a 400, but a shifted 5xx line would vanish from your count in the same way. Splitting on " makes the request line one field whatever it contains, and the status is then the first word of the third field. When the two methods give different totals, look for malformed lines before you trust either number.

04. Check your understanding

Practice check · 3 questions

Pipeline stream processing, awk filtering, and uniq verification

Three questions on cut, redirection and awk fields.

Q1. `sizes.txt` has a header line `NAME SIZE` and pads both columns so that they line up. `cut -d" " -f2 sizes.txt` prints only empty lines, while `awk '{print $2}' sizes.txt` prints `SIZE` and the sizes. Why?
Q2. What is left in `access.log` after you run `sort access.log > access.log`?
Q3. A log line has the request `"-"` instead of `"GET /x HTTP/1.1"`. What does `awk '{print $9}'` print for that line?
Practice only: not graded, not saved, not evidence.

05. Apply it

Use these shell processing workflows when investigating live server incidents:

  • Isolate Top Slow Endpoints: If Nginx logs include request duration in field 11, run awk '$11 > 1.0 { print $7, $11 }' access.log | sort -k2 -rn | head -n 10 to list the slowest requests first.
  • Detect Brute Force Login Attempts: For authentication logs, extract client IPs hitting /api/v1/auth/login and pipe through sort | uniq -c | sort -rn | head -n 20 to find the addresses that try most often; a high count is a lead to investigate, not proof of an attack.
  • Clean Log Pipelines: When a filter and a field extraction can be one awk program, prefer it to a chain of grep and cut: it is one process instead of several, and the field logic sits in one place.

06. Review prompt

Explain how POSIX standard streams are represented by file descriptors 0, 1, and 2. Detail why ./run.sh > out.log 2>&1 behaves differently from ./run.sh 2>&1 > out.log. Describe why uniq -c requires pre-sorted input and construct an awk command that filters for response sizes greater than 10 kilobytes.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check