#Why this matters
During incident response or Linux CTF challenges, you often land on a minimal host over SSH where Python libraries or graphical log viewers are absent. Bash lets you chain built-in Unix tools to inspect hundreds of log files, filter noise, and extract indicators of compromise directly from the terminal.
Building on the regular expressions and automation concepts from earlier lessons, Bash focuses on text streams: lines of data flowing from one focused utility into the next. Writing clean loops and functions turns ad-hoc one-liners into repeatable scripts you can trust under pressure.
#Safe script foundations and quoting
Start every Bash script with a portable shebang and strict mode so silent failures cannot cascade through a pipeline:
#!/usr/bin/env bash
set -euo pipefail| Setting | Purpose | Risk prevented |
|---|---|---|
set -e |
Exit if a command returns non-zero | Continuing after a missing file or failed copy |
set -u |
Treat unset variables as errors | Expanding an empty path such as rm -rf "$DIR/" |
set -o pipefail |
Fail a pipeline if any stage fails | Masking an upstream grep or curl error |
Always wrap variable expansions in double quotes ("$file", "$line"). Without quotes, Bash splits values on spaces and expands wildcard characters like *, which breaks filenames containing spaces and can alter command flags.
#Loops and functions for batching tasks
Use shell globs to loop over files safely instead of parsing command output. Guard empty directories so a literal pattern like *.log is skipped when no files match:
#!/usr/bin/env bash
set -euo pipefail
extract_denied_ips() {
local log_file="$1"
local status_code="${2:-403}"
if [[ ! -f "$log_file" ]]; then
echo "Missing file: $log_file" >&2
return 1
fi
awk -v code="$status_code" '$3 == code { print $1 }' "$log_file"
}
for path in /tmp/lab-logs/*.log; do
[[ -e "$path" ]] || continue
extract_denied_ips "$path" "401"
done | sort | uniq -c | sort -rnTwo details make this pattern reliable:
localvariables: Keeplog_fileandstatus_codescoped insideextract_denied_ipsso they do not overwrite variables in the caller.- Line-by-line reads: When a loop must inspect each line in Bash rather than
awk, usewhile IFS= read -r line; do ... done < "$path". SettingIFS=preserves leading and trailing spaces, and-rstops backslashes from being treated as escapes.
#Processing text streams with sed and awk
A Unix pipeline connects standard output (stdout, descriptor 1) of one command to standard input (stdin, descriptor 0) of the next, while errors go to standard error (stderr, descriptor 2). Each stage narrows or reshapes the stream:
- Readcat or grep -E
- Cleansed (strip noise or mask tokens)
- Extractawk -F (select fields)
- Aggregatesort and uniq -c
Use sed for line-level edits and masking, and awk when lines have columns or delimiters:
sed -n '10,25p' app.log: Print only lines 10 through 25.sed -E '/^(#|$)/d' rules.conf: Delete comment and empty lines.awk -F',' '$4 >= 500 { print $1, $2, $4 }' access.csv: Split on commas and print fields when column 4 is 500 or higher.
$ cat sample_http.log
192.0.2.15 GET 200 /index.html
192.0.2.44 POST 401 /login
192.0.2.44 POST 401 /login
192.0.2.81 GET 401 /admin
192.0.2.44 POST 401 /api/token
$ awk '$3 == "401" { print $1 }' sample_http.log | sort | uniq -c | sort -rn
3 192.0.2.44
1 192.0.2.81Notice why sort comes right before uniq -c: uniq only collapses adjacent duplicate lines.
#Common mistakes and defensive checks
- Parsing
lsoutput:for f in $(ls *.log)breaks on filenames with spaces or newlines. Always use shell globs (for f in *.log) orfind ... -print0paired withwhile IFS= read -r -d '' f. - Omitting
sortbeforeuniq: Runninguniq -con unsorted streams leaves duplicate keys scattered across the output. - Passing shell variables directly into
awkquotes: Writingawk "\$3 == $code"invites syntax bugs or injection if$codecontains spaces; pass values cleanly withawk -v code="$code". - Skipping static checks: Run
bash -n script.shto catch syntax issues and use ShellCheck when available to flag unquoted expansions and unused variables before running scripts as root.
#Summary
- Strict mode (
set -euo pipefail) and double-quoted variables ("$var") prevent silent failures and word-splitting bugs in Bash scripts. - Shell globs,
localvariables, andwhile IFS= read -rloops let functions process batches of files safely, even when paths contain spaces. - Chaining
sed,awk,sort, anduniq -cturns raw multi-file logs into ranked summaries without external dependencies. - Avoid parsing
lsand never interpolate untrusted text directly insideevalorawkprogram strings.