Перейти к основному содержимому
Bash Scripting: Loops, Functions & Text Streams
Урок 7 из 10

Bash Scripting: Loops, Functions & Text Streams

Write safe Bash scripts using strict mode, loops, and functions, and build sed and awk text-stream pipelines to parse security logs in batches.

Средний 25 мин Программирование
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Configure Bash strict mode and safe variable quoting to prevent word-splitting bugs
  • Automate multi-file triage using for loops, while-read loops, and reusable functions
  • Transform and summarize structured log lines using sed and awk stream pipelines
  • Identify common shell scripting pitfalls such as unquoted variables and parsing ls output

Рекомендуется заранее: Regular Expressions for Logs & Indicator ExtractionWriting Security Automation & Parsing Pipelines

#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:

bash
#!/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:

bash
#!/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 -rn

Two details make this pattern reliable:

  • local variables: Keep log_file and status_code scoped inside extract_denied_ips so they do not overwrite variables in the caller.
  • Line-by-line reads: When a loop must inspect each line in Bash rather than awk, use while IFS= read -r line; do ... done < "$path". Setting IFS= preserves leading and trailing spaces, and -r stops 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:

  1. Readcat or grep -E
  2. Cleansed (strip noise or mask tokens)
  3. Extractawk -F (select fields)
  4. 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.
Counting repeated HTTP 401 sources in a lab log
$ 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.81

Notice why sort comes right before uniq -c: uniq only collapses adjacent duplicate lines.

#Common mistakes and defensive checks

  • Parsing ls output: for f in $(ls *.log) breaks on filenames with spaces or newlines. Always use shell globs (for f in *.log) or find ... -print0 paired with while IFS= read -r -d '' f.
  • Omitting sort before uniq: Running uniq -c on unsorted streams leaves duplicate keys scattered across the output.
  • Passing shell variables directly into awk quotes: Writing awk "\$3 == $code" invites syntax bugs or injection if $code contains spaces; pass values cleanly with awk -v code="$code".
  • Skipping static checks: Run bash -n script.sh to 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, local variables, and while IFS= read -r loops let functions process batches of files safely, even when paths contain spaces.
  • Chaining sed, awk, sort, and uniq -c turns raw multi-file logs into ranked summaries without external dependencies.
  • Avoid parsing ls and never interpolate untrusted text directly inside eval or awk program strings.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания