Lesson 2 — Linux & Bash Command-Line Operations
Course: DevOps & Platform Engineering (devops) · Group: Data Engineering
Workplace: Northline (illustrative synthetic organisation)
Assumed environment: Ubuntu 22.04 LTS, bash 5.1.x (illustrative). Commands shown are POSIX-compatible unless noted. Exact behaviour may vary on macOS (zsh default) or WSL. Always verify on your actual system.
Status: approved
Learning objectives & deliverable
By the end of this lesson you will be able to:
- Navigate a Linux filesystem and inspect permissions, ownership, and file metadata.
- Manage running processes: list them, inspect resource usage, and send signals safely.
- Combine commands with pipes, redirection, and filters to extract information from log output.
- Use
grep,find,sed, andawkappropriately for searching and transforming text. - Make safe, verified HTTP requests with
curland work withtararchives. - Write a basic, well-structured shell script with exit-code handling, argument validation, and quoting.
- Understand scheduling concepts and when to reach for
cron-style tooling. - Identify and avoid destructive commands; apply safe-execution habits.
Deliverable: A shell script northline_log_check.sh that: (a) accepts a log file path as an argument, (b) counts lines containing the string ERROR, (c) prints a human-readable summary, and (d) exits with code 1 if the error count exceeds a configurable threshold. Validated with two test log files provided in the guided-practice section.
Prerequisites
| Concept | Where to learn it |
|---|---|
| DevOps delivery lifecycle overview | Lesson 1 — DevOps & Platform Engineering #devops1 |
| Version control basics | Git Foundations #git1–#git4 |
| What a pipeline step is | #devops1 §5, #devops4 |
No cloud account is required. A local Ubuntu 22.04 LTS machine, WSL2, or a free online shell (e.g., Killercoda Ubuntu playground — pricing and availability are environment-dependent; verify current access) is sufficient.
Lesson opener
In one line: The command line is the universal control surface of every Linux server, CI runner, and container — knowing it well is the difference between diagnosing a problem in two minutes and staring at a black screen for an hour.
Why it matters: Every pipeline step in #devops4 runs as a shell command inside a Linux container. Every deployment artefact is assembled by shell scripts. Every log investigation in a data engineering incident starts with grep, tail, and pipes. Fluency here compounds across every other lesson in this course and into every cloud, MLOps, and platform engineering context.
Before this lesson: Lesson 1 #devops1 for delivery lifecycle context. Basic file awareness (what a file and directory are) from general computer literacy.
Northline's on-call data engineer received a PagerDuty alert at 02:14 on a Tuesday: the stream-processor pipeline had stopped writing records to the data lake. The alert contained a container name and a node hostname. Everything from that point — checking running processes, reading compressed log archives, filtering 400,000 log lines for the 12 that described the failure, and verifying the fix — was done at the command line. This lesson teaches exactly those skills.
1. Filesystem Navigation
1.1 Core commands
# Show current directory
pwd
# List files and directories
ls # basic listing
ls -l # long format: permissions, owner, size, timestamp
ls -lh # human-readable sizes
ls -la # include hidden files (names starting with .)
ls -lt # sort by modification time, newest first
# Change directory
cd /var/log # absolute path
cd logs # relative path
cd .. # parent directory
cd ~ # home directory
cd - # previous directory
# Create and remove directories
mkdir reports
mkdir -p reports/2026/q4 # create intermediate parents
rmdir empty-dir # only works on empty directoriesIllustrative assumption: Path examples use
/var/logand similar Linux standard paths. WSL2 paths differ (e.g.,C:\mounts as/mnt/c/).
1.2 File metadata
# File type and basic info
file /etc/hosts # shows file type, encoding
# Disk usage of a directory tree
du -sh /var/log # -s: summary, -h: human-readable
du -sh /var/log/* # per subdirectory
# inode and hard-link information
stat /etc/hosts1.3 Safe habits
- Never run commands as root unless necessary. Use
sudofor specific privileged operations only. - Always check
pwdbefore runningrmormv. The wrong working directory with a wildcard is unrecoverable. - Use
lsbeforerm -ron any pattern. Confirm what you are about to delete.
2. File Permissions and Ownership
2.1 Reading permissions
The ls -l output for a file looks like:
-rw-r--r-- 1 northline-svc data-eng 2048 Sep 28 14:22 pipeline.log
^ ^ ^ ^
| | | group
| | owner
| hard-link count
permission stringThe permission string has 10 characters:
- Character 1: file type (
-file,ddirectory,lsymlink). - Characters 2–4: owner permissions (r=read, w=write, x=execute).
- Characters 5–7: group permissions.
- Characters 8–10: other (everyone else) permissions.
2.2 Changing permissions
# Symbolic mode (preferred — explicit and readable)
chmod u+x script.sh # add execute for owner
chmod go-w sensitive.conf # remove write for group and other
chmod u=rw,go=r config.yml # set exactly: owner rw, others r
# Octal mode (common in scripts and documentation)
chmod 644 config.yml # rw-r--r--
chmod 755 deploy.sh # rwxr-xr-x
chmod 600 private_key.pem # rw------- (owner only)Security note: SSH private keys must be
600; most SSH clients refuse to use keys with looser permissions.
2.3 Changing ownership
# Requires sudo unless you own the file
sudo chown northline-svc:data-eng pipeline.log # user:group
sudo chown -R northline-svc /app/data # recursive; use carefully2.4 setuid, setgid, sticky bit (awareness only)
These special bits are outside day-to-day data engineering work but appear in security audits. chmod 4755 sets setuid; chmod 1777 sets sticky bit (used on /tmp). Do not set setuid/setgid on scripts you write unless you specifically understand the security implications.
3. Process Management
3.1 Listing processes
# All processes, full format
ps aux
# Search for a specific process
ps aux | grep python
# Interactive process viewer (press q to quit)
top
# Or the improved version (may need installation)
htopThe ps aux columns: USER, PID, %CPU, %MEM, VSZ (virtual memory KB), RSS (resident memory KB), STAT, START, TIME, COMMAND.
3.2 Process signals
# Graceful termination (SIGTERM — gives the process time to clean up)
kill 12345 # by PID
kill -15 12345 # explicit SIGTERM (15 is the default)
kill -TERM 12345 # named form
# Force kill (SIGKILL — immediate, no cleanup; use only if SIGTERM fails)
# ⚠️ DESTRUCTIVE: the process cannot write pending buffers or release file locks
kill -9 12345
kill -KILL 12345
# Kill by name (use carefully — matches all processes with that name)
pkill python
killall python
# Background and foreground
command & # run in background
jobs # list background jobs
fg %1 # bring job 1 to foreground
bg %1 # resume job 1 in background
Ctrl+C # send SIGINT to foreground process
Ctrl+Z # suspend foreground process (SIGTSTP)⚠️ Caution:
kill -9is a last resort. It prevents the process from releasing locks, flushing write buffers, or running shutdown hooks. Usekill(SIGTERM) first and wait 5–10 seconds.
3.3 Finding what is using a port
# Which process is listening on port 8080?
ss -tlnp | grep 8080
# Or:
lsof -i :80804. Pipes, Redirection, and Filters
4.1 Redirection
# Redirect stdout to a file (overwrite)
echo "hello" > output.txt
# Append stdout to a file
echo "world" >> output.txt
# Redirect stderr to a file
command 2> errors.txt
# Redirect both stdout and stderr
command > output.txt 2>&1
command &> output.txt # bash shorthand
# Discard output
command > /dev/null 2>&1
# Read from a file instead of stdin
command < input.txt4.2 Pipes
The pipe | connects the stdout of one command to the stdin of the next. Commands run concurrently; data flows in a stream.
# Count lines containing ERROR in a log file
cat pipeline.log | grep ERROR | wc -l
# Equivalent (cat is unnecessary — this is preferred)
grep ERROR pipeline.log | wc -l
# Most recent 50 log lines, filtered for errors, sorted
tail -n 50 pipeline.log | grep ERROR | sort
# Real-time log filtering (follows the file as it grows)
tail -f pipeline.log | grep --line-buffered ERROR4.3 Reading compressed logs (common in production)
# View a gzip-compressed log without decompressing it first
zcat pipeline.log.gz | grep ERROR
# Same with xz-compressed files
xzcat pipeline.log.xz | grep ERROR5. grep, find, sed, and awk
5.1 grep — searching text
# Basic search
grep "ERROR" pipeline.log
# Case-insensitive
grep -i "error" pipeline.log
# Show line numbers
grep -n "ERROR" pipeline.log
# Show N lines of context before and after the match
grep -B 2 -A 5 "ERROR" pipeline.log
# Recursive search in a directory
grep -r "kafka_topic" /app/config/
# Count matches
grep -c "ERROR" pipeline.log
# Invert: show lines that do NOT match
grep -v "DEBUG" pipeline.log
# Extended regex (use -E for |, +, ?, {})
grep -E "ERROR|WARN" pipeline.log
# Print only the matching part (not the full line)
grep -o "topic=[^ ]*" pipeline.logPattern quoting: Always single-quote grep patterns unless you specifically need shell variable expansion. Double-quotes allow
$varexpansion; single-quotes treat everything literally.grep '$amount'searches for the literal dollar sign;grep "$amount"searches for the value of the variableamount.
5.2 find — searching the filesystem
# Find files by name
find /app -name "*.log"
# Find files modified in the last 24 hours
find /var/log -name "*.log" -mtime -1
# Find files larger than 100 MB
find /data -size +100M
# Find and execute a command on each result
# -exec runs the command once per file; {} is replaced by the filename
find /app -name "*.pyc" -exec rm {} \;
# Find and print with detail
find /app -name "*.log" -exec ls -lh {} \;
# Find directories only
find /app -type d -name "config"⚠️ Caution:
find ... -exec rm {} \;is destructive. Always runfind ... -printfirst to confirm what will be matched before adding-exec rm.
5.3 sed — stream editor (awareness level)
sed performs text transformations on streams. Data engineering work most commonly uses it for simple substitutions in scripts or pipeline steps.
# Replace first occurrence per line
sed 's/old/new/' file.txt
# Replace all occurrences per line
sed 's/old/new/g' file.txt
# In-place edit (modifies the file; -i makes a backup with extension .bak)
sed -i.bak 's/localhost/db.northline.internal/g' config.yml
# Delete lines matching a pattern
sed '/^#/d' config.yml # remove comment lines
# Print only lines 10–20
sed -n '10,20p' file.txtNote on
sed -iwithout backup:sed -i 's/old/new/g' file(no backup suffix) overwrites the original with no recovery path. Always usesed -i.bakor commit the file to version control before editing in place. Verify withdiff file.bak fileafterwards.
5.4 awk — column processing (awareness level)
awk processes text row by row and is particularly useful for tab- or space-delimited data. It is a complete programming language; this section covers the patterns used in data engineering pipeline debugging.
# Print specific columns from space-delimited output
ps aux | awk '{print $1, $2, $11}' # user, PID, command
# Filter rows where column 3 exceeds a threshold
awk '$3 > 50 {print $0}' ps_output.txt
# Sum a column
awk '{sum += $2} END {print "Total:", sum}' numbers.txt
# Field separator: process CSV (simple, no quoted fields)
awk -F',' '{print $1, $3}' data.csv
# Print the number of fields in each line (useful for diagnosing malformed CSV)
awk -F',' '{print NR, NF, $0}' data.csvAwareness note:
awkandsedare powerful but have edge cases with Unicode, binary data, and quoting. For production data transformation scripts, consider Python (pandas, polars) or a dedicated ETL tool. Useawk/sedfor quick log inspection and simple pipeline glue.
6. curl — HTTP from the Command Line
curl sends HTTP requests and is the standard tool for testing endpoints, downloading files, and querying APIs from scripts.
# GET request
curl https://httpbin.org/get
# Show response headers
curl -I https://httpbin.org/get # HEAD request (headers only)
curl -v https://httpbin.org/get # verbose: shows request and response headers
# POST JSON data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"status": "ok"}' \
https://httpbin.org/post
# Download a file
curl -O https://example.com/archive.tar.gz # saves with original filename
curl -o local_name.tar.gz https://example.com/archive.tar.gz
# Follow redirects
curl -L https://example.com/redirect
# Check only the HTTP status code
curl -o /dev/null -s -w "%{http_code}\n" https://example.com/health
# Silent mode (no progress bar) — useful in scripts
curl -s https://api.example.com/statusSecurity notes:
- Never pass credentials (tokens, passwords) as command-line arguments in shared environments — they appear in process listings. Use environment variables:
curl -H "Authorization: Bearer $API_TOKEN".- Never disable TLS verification (
--insecure/-k) in production scripts. Doing so silently removes the protection against man-in-the-middle attacks.-
httpbin.orgis a public test service; pricing and availability are environment-dependent. Do not send real credentials or production data to it.
7. Archives — tar
tar (tape archive) is the standard tool for bundling and compressing files on Linux. CI/CD pipeline artefact steps use it extensively.
# Create a compressed archive (gzip)
tar -czf archive.tar.gz directory/
# -c: create, -z: gzip compression, -f: filename
# Create with xz compression (better ratio, slower)
tar -cJf archive.tar.xz directory/
# List contents without extracting
tar -tzf archive.tar.gz
# Extract to current directory
tar -xzf archive.tar.gz
# Extract to a specific directory
tar -xzf archive.tar.gz -C /target/directory/
# Extract a single file from the archive
tar -xzf archive.tar.gz archive/specific_file.txt
# Verbose output (list files as they are processed)
tar -xzvf archive.tar.gz⚠️ Extraction path traversal: Never extract archives from untrusted sources without first listing their contents (
tar -tzf). Malicious archives can contain paths like../../etc/crontabthat write outside the intended directory. Check that all paths in the archive are relative and do not start with/.
8. Exit Codes
Every command in Linux exits with a numeric code. 0 means success. Any non-zero value means failure (convention: 1 general error, 2 misuse of command, higher values are command-specific).
# Check the exit code of the last command
echo $?
# Practical example
grep "ERROR" pipeline.log
echo $? # 0 if match found, 1 if no match, 2 if error (file not found)8.1 Using exit codes in scripts
#!/usr/bin/env bash
set -euo pipefail # e: exit on error, u: undefined var error, o pipefail: pipe fails if any command fails
if ! grep -q "ERROR" pipeline.log; then
echo "No errors found."
exit 0
fi
error_count=$(grep -c "ERROR" pipeline.log)
echo "Found ${error_count} errors."
exit 18.2 set -euo pipefail — the safety belt
| Option | Effect |
|---|---|
set -e | Script exits immediately if any command returns non-zero |
set -u | Script exits if an unset variable is referenced |
set -o pipefail | A pipeline fails if any command in the pipeline fails (not just the last) |
Without set -o pipefail, grep ERROR huge.log | wc -l returns exit code 0 even if grep fails — because wc -l succeeds. With pipefail, the failure propagates.
9. Shell Scripts — Structure and Safe Patterns
9.1 Script skeleton
#!/usr/bin/env bash
# Script: northline_log_check.sh
# Purpose: Count ERROR lines in a log file; exit 1 if count exceeds threshold
# Usage: ./northline_log_check.sh <log_file> [threshold]
# Dependencies: bash 5.x, grep, wc
# Illustrative script — test in a non-production environment first
set -euo pipefail
# --- Argument validation ---
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <log_file> [threshold]" >&2
exit 2
fi
LOG_FILE="$1"
THRESHOLD="${2:-100}" # default threshold: 100
if [[ ! -f "$LOG_FILE" ]]; then
echo "Error: log file '$LOG_FILE' not found." >&2
exit 2
fi
# --- Main logic ---
error_count=$(grep -c "ERROR" "$LOG_FILE" || true)
# '|| true' prevents set -e from exiting when grep finds 0 matches (exit code 1)
echo "Log file : $LOG_FILE"
echo "Errors : $error_count"
echo "Threshold: $THRESHOLD"
if (( error_count > THRESHOLD )); then
echo "ALERT: error count exceeds threshold." >&2
exit 1
fi
echo "OK: error count within threshold."
exit 09.2 Quoting rules
Incorrect quoting is the source of a large fraction of shell script bugs, especially when filenames contain spaces.
FILE="my log file.txt"
# WRONG — breaks on spaces; word-splits into three arguments
grep ERROR $FILE
# CORRECT — preserves filename as one argument
grep ERROR "$FILE"
# WRONG — glob expansion; * expands to matching filenames
for f in $FILES; do ...
# CORRECT
for f in "$FILES"; do ...
# SAFE pattern for iterating arrays
files=("file one.txt" "file two.txt")
for f in "${files[@]}"; do
echo "Processing: $f"
doneRule of thumb: Double-quote every variable expansion unless you specifically need word-splitting or glob expansion. If in doubt, quote.
9.3 Avoiding destructive commands
| Command | Risk | Safe alternative or safeguard |
|---|---|---|
rm -rf /path | Deletes recursively; irreversible | ls /path first; confirm path with pwd; use trash-cli on workstations |
rm -rf /* | Deletes entire filesystem — do not run | Never use * at root level; add a path sanity check in scripts |
chmod -R 777 / | Opens all permissions recursively | Never use recursive chmod without an explicit, narrow path |
> file | Truncates (empties) the file immediately | Use >> file to append; or rename the file as backup first |
dd if=/dev/zero of=/dev/sda | Overwrites disk | Never run dd with a block device target without expert supervision |
kill -9 1 | Kills init/systemd — crashes the system | Never send signals to PID 1 |
Destructive commands note: The
rm -rf /*andddexamples are shown for educational awareness only. They are marked as dangerous and should never be executed. If you encounter them in documentation or a script, treat them as a red flag.
10. Scheduling Awareness
Shell scripts are often run on a schedule. The most common mechanism on Linux is cron.
# View current user's crontab
crontab -l
# Edit crontab (opens in $EDITOR)
crontab -eCrontab format:
# MIN HOUR DAY MONTH WEEKDAY COMMAND
0 2 * * * /opt/northline/scripts/northline_log_check.sh /var/log/stream-processor.log 50This runs the script every day at 02:00.
Scheduling considerations:
- Cron jobs run in a minimal environment;
PATH, environment variables, and shell functions available in your interactive session are not available. Specify full absolute paths to all binaries.- Capture output:
command >> /var/log/cron_output.log 2>&1- For production scheduling at Northline, the platform team provides a managed job scheduler (environment-dependent tooling). Cron is used for workstation automation and simple server-side tasks.
-
systemdtimers are the modern alternative to cron on Ubuntu 22.04. Awareness of both is useful; your team's choice depends on infrastructure.
Worked Example A — Diagnosing the Stream-Processor Incident
Context: The on-call engineer receives an alert: stream-processor has stopped writing records. Container name: stream-proc-7f8b9d-xkp2q. Node hostname: northline-node-04 (illustrative).
# 1. SSH to the node (or exec into the container)
# Illustrative — actual access method is environment-specific
kubectl exec -it stream-proc-7f8b9d-xkp2q -- /bin/bash
# 2. Check what is running
ps aux | grep python
# 3. Find the log file
find /app -name "*.log" -mtime -1
# 4. Count errors quickly
grep -c "ERROR" /app/logs/stream-processor.log
# 5. Get context around the first error
grep -n "ERROR" /app/logs/stream-processor.log | head -5
# e.g., output: 41823:2026-09-30T02:14:03Z ERROR KafkaConsumer: broker connection refused
# 6. Get 10 lines of context around line 41823
sed -n '41810,41835p' /app/logs/stream-processor.log
# 7. Check if the Kafka broker is reachable
curl -s -o /dev/null -w "%{http_code}" http://kafka-broker.northline.internal:8080/health
# (illustrative endpoint — actual broker health check varies by Kafka distribution)
# 8. Check recent config changes
find /app/config -name "*.yml" -mtime -1 -exec ls -lh {} \;Finding: The Kafka broker address in /app/config/consumer.yml pointed to localhost:9092 instead of kafka-broker.northline.internal:9092. A recent config file substitution had introduced a bug.
Fix:
# Verify current value
grep "kafka" /app/config/consumer.yml
# Fix (with backup)
sed -i.bak 's/localhost:9092/kafka-broker.northline.internal:9092/g' /app/config/consumer.yml
# Verify
diff /app/config/consumer.yml.bak /app/config/consumer.yml
# Restart the process (illustrative — use your platform's restart mechanism)
# The correct mechanism is to trigger a re-deploy from the platform portal, not to restart manually in productionWorked Example B — Artefact Packaging in a CI Step
A CI pipeline step packages the Python application as a compressed archive for deployment.
#!/usr/bin/env bash
# Illustrative CI packaging step — not production-ready as written
set -euo pipefail
VERSION="${GIT_SHA:-unknown}"
DIST_DIR="dist"
mkdir -p "$DIST_DIR"
# Exclude virtualenv, caches, test fixtures
tar -czf "${DIST_DIR}/stream-processor-${VERSION}.tar.gz" \
--exclude='.git' \
--exclude='__pycache__' \
--exclude='*.pyc' \
--exclude='.venv' \
--exclude='tests/fixtures' \
src/ requirements.txt config/
# Verify the archive is non-empty and valid
if ! tar -tzf "${DIST_DIR}/stream-processor-${VERSION}.tar.gz" > /dev/null 2>&1; then
echo "ERROR: archive is invalid or empty." >&2
exit 1
fi
echo "Artefact created: ${DIST_DIR}/stream-processor-${VERSION}.tar.gz"
ls -lh "${DIST_DIR}/stream-processor-${VERSION}.tar.gz"Failure Scenario — Script Fails Silently on Missing File
Symptom: northline_log_check.sh always exits 0 and reports "0 errors", even when the log file has errors.
Diagnosis:
# Run the script with a non-existent file
./northline_log_check.sh /tmp/does_not_exist.log
# Output: "Errors: 0" (incorrect — should error)Root cause: The script was written without set -euo pipefail and without checking whether the file exists before running grep. When grep fails to open the file, it exits with code 2, but the exit code was not checked. The $(grep -c ...) subshell captured empty output, which was treated as 0.
Correction: Add set -euo pipefail at the top of the script and add explicit argument and file-existence validation (as shown in §9.1).
Validation:
# Test 1: missing file should exit 2
./northline_log_check.sh /tmp/does_not_exist.log; echo "Exit: $?"
# Expected: exit 2 with error message
# Test 2: file with errors below threshold should exit 0
printf 'INFO ok\nERROR bad\nINFO ok\n' > /tmp/test.log
./northline_log_check.sh /tmp/test.log 10; echo "Exit: $?"
# Expected: "Errors: 1", exit 0
# Test 3: file with errors above threshold should exit 1
printf '%s\n' $(python3 -c "print('\n'.join(['ERROR x']*150))") > /tmp/test_over.log
./northline_log_check.sh /tmp/test_over.log 100; echo "Exit: $?"
# Expected: "ALERT: error count exceeds threshold.", exit 1Prevention: Always validate inputs at the top of a script. Always run scripts through shellcheck (a static analysis tool for shell scripts) before committing.
Guided Practice
Task: Complete the northline_log_check.sh script from §9.1. Then test it using the two log files below.
Test log file 1 — test_ok.log:
2026-09-30T01:00:01Z INFO Consumer started
2026-09-30T01:00:05Z INFO Connected to broker
2026-09-30T01:00:10Z WARN Retry 1 of 3
2026-09-30T01:00:15Z INFO Records written: 200
2026-09-30T01:00:20Z ERROR Deserialization failed: bad schema
2026-09-30T01:00:25Z INFO Records written: 198Test log file 2 — generate with:
# This command is illustrative and safe to run on a test system
python3 -c "
import sys
for i in range(120):
print(f'2026-09-30T01:{i//60:02d}:{i%60:02d}Z ERROR Kafka timeout #{i}')
for i in range(30):
print(f'2026-09-30T02:{i//60:02d}:{i%60:02d}Z INFO Recovered')
" > /tmp/test_over_threshold.logExpected behaviour:
./northline_log_check.sh test_ok.log 100→ exit 0, reports 1 error../northline_log_check.sh /tmp/test_over_threshold.log 100→ exit 1, reports 120 errors.
Full solution: The complete script is provided in §9.1. Copy it verbatim, make it executable with chmod +x northline_log_check.sh, and run the two test cases. Confirm exit codes with echo $? after each run.
Independent Practice
Task: Extend northline_log_check.sh with the following capabilities:
- Accept a third argument
--pattern <string>that overrides the default search patternERROR. - Output the most recent five matching lines as a preview in the summary.
- Support gzip-compressed log files (
.log.gz) automatically (usezcatif the filename ends in.gz).
Acceptance criteria:
- Script passes
shellcheckwith no errors or warnings. - All three test cases below pass:
- ./northline_log_check.sh test_ok.log 100 → exit 0, shows 1 ERROR.
- ./northline_log_check.sh test_ok.log 0 → exit 1.
- gzip -c test_ok.log > test_ok.log.gz && ./northline_log_check.sh test_ok.log.gz 100 → exit 0, same result.
- No hardcoded paths; all file access goes through the
"$LOG_FILE"variable. - No use of
cat file | grep(usegrep filedirectly).
Common Mistakes
- Forgetting
set -euo pipefail. Scripts silently continue after failures. The most dangerous bugs are the ones that produce no error message. - Using
kill -9as a first resort. Always trykill(SIGTERM) first and wait. SIGKILL prevents clean shutdown. - Unquoted variables with spaces.
grep ERROR $LOG_FILEbreaks whenLOG_FILEcontains a space. Always double-quote. find -exec rm {} \;withoutfind -printfirst. The pattern, the path, and the permissions are not always what you expect. Confirm the match set before deleting.- Embedding credentials in scripts. Never hardcode tokens, passwords, or connection strings. Use environment variables injected at runtime. See #devops3 for secrets prevention in Git.
- Running
grepon a compressed file directly.grep ERROR pipeline.log.gzsearches the binary compressed data, not the text content. Usezcat pipeline.log.gz | grep ERROR. - Ignoring exit codes. A script that checks
$?only at the end has no idea which step failed. Useset -eor explicit|| exit Nafter each critical step.
Five Quick Checks
Q1. A file has permissions 640. What can the owner, group members, and others do?
A1. Owner: read and write. Group: read only. Others: no access at all.
Q2. A colleague runs grep ERROR access.log | wc -l and gets 0. You know there are errors. What is one likely cause?
A2. The search is case-sensitive. The log might contain error (lowercase) instead of ERROR. Try grep -i error access.log | wc -l.
Q3. What does set -o pipefail do?
A3. It causes a pipeline to return the exit code of the first failing command, not just the last. Without it, false | true exits 0 even though false failed.
Q4. How do you check what process is listening on port 5432?
A4. ss -tlnp | grep 5432 or lsof -i :5432. Both show the PID and process name.
Q5. Why should you never pass an API token as a command-line argument?
A5. Command-line arguments are visible in ps aux output and in shell history to any user with process-listing permissions on the same machine. Use environment variables injected at runtime instead.
Quiz Alignment
| Objective | Quick Check | Practice task |
|---|---|---|
| Navigate filesystem and inspect permissions | Q1 | Guided practice — read log files |
| Manage processes safely | Q4 | Worked Example A — ps aux step |
| Use pipes and grep effectively | Q2 | Deliverable script |
| Exit codes and safe scripts | Q3 | Failure Scenario |
| curl and secrets safety | Q5 | Worked Example A — curl step |
| Archives | — | Worked Example B; Independent practice |
Lesson Takeaways
- Linux filesystem navigation, permissions, and process management are foundational skills for every pipeline step, container debugging session, and deployment incident.
grep,find,sed, andawkare the four core text-processing tools; knowing when to use each (and when to reach for Python instead) distinguishes a fluent operator from a copy-paste practitioner.set -euo pipefailis the single most important safety practice for shell scripts.- Always quote variable expansions. Always confirm what
findwould delete before adding-exec rm. - Exit codes are a contract:
0is success, non-zero is failure. Use them deliberately and check them explicitly.
Bridge to Next Lesson
In Lesson 3 — Git Workflows & Collaborative Delivery (#devops3), you will learn the enterprise Git patterns that govern how teams collaborate at scale: pull request workflows, merge strategies, trunk-based development, protected branches, tag and semver conventions, conflict resolution, commit hygiene, and how to prevent secrets from entering a repository. The shell skills from this lesson will be used directly — you will run git commands, inspect logs with pipes and grep, and write pre-commit hook scripts.