Linux Commands (Text Processing, File Search, and Permissions)

The Linux command line uses the shell to coordinate commands, file descriptors, and pipelines to operate the system; this tutorial focuses on text processing, file discovery, and mode permissions on GNU/Linux, noting that not every command reads standard input and writes standard output.

Second-Draft Verification Note (2026-10-15): Concepts, applicability conditions, and example walkthroughs have been revised against the official documentation and primary sources listed at the end. The Debian and utility versions and command outputs reported in Draft 1 are retained as historical source records and do not represent execution proof on the current Windows / Python 3.12.14 environment; refer to the companion verification log for the execution scope of this batch. All product names, accounts, datasets, and credentials in the examples are fictional.

One-Sentence Definition

The Linux command line uses a shell to coordinate commands, file descriptors, and pipelines to operate the system; this tutorial focuses on text processing, file search, and file mode permissions on GNU/Linux, keeping in mind that not every command simultaneously reads from standard input and writes to standard output.

Scope Boundaries & Practical Judgment

Always verify the input format before picking a text tool: the synthetic access log in our example uses whitespace-separated columns with no embedded spaces, which is why column extraction with awk works cleanly. JSON logs, quoted CSVs, or fields containing newlines should be handled by dedicated parsers instead. Remember that uniq only collapses adjacent duplicate lines; pairing find -print0 with xargs -0 solves filename delimiter splitting but does not replace auditing command arguments and target directories. Sorting order also depends on the active locale — set LC_ALL=C explicitly whenever you need reproducible byte-order sorting. References: GNU Coreutils Manual; Bash set Builtin Manual.

Why It Matters

  • Production servers, GPU instances, and containers almost universally run Linux; when diagnosing live incidents, an SSH terminal is often the only interface available.
  • For log triage, batch file operations, and disk or permission checks, composing command-line pipelines is often much faster than writing a custom script.
  • Reviewing shell commands proposed by AI coding assistants — especially rm, chmod -R, or find -delete — requires reading them fluently (see k6.ops.shell-script for safe script structure).

How It Works / Diagram

GNU Coreutils Manual: https://www.gnu.org/software/coreutils/manual/; GNU Awk Manual: https://www.gnu.org/software/gawk/manual/; POSIX Utilities Specification: https://pubs.opengroup.org/onlinepubs/9799919799/idx/utilities.html

Figure 1
Task Commands
Inspect files head, tail, less, wc -l
Filter lines grep 'pattern', grep -v (invert match), grep -c (count matches)
Extract columns / compute awk '{print $2}', cut -d' ' -f1
Sort & count sort, sort -n (numeric), uniq -c (merges adjacent duplicates only, so sort first)
Substitute text sed 's/old/new/g', tr
Find files find . -name '*.log' -size +10k -mtime +7
Batch execution xargs (pair with find -print0 / xargs -0 to handle filenames containing spaces safely)
Disk usage df -h, du -sh *
Permissions ls -l, chmod, chown

Runnable Example

Example Version & Verification Scope

The code and output below preserve the instructional design from Draft 1. Branches involving Linux utilities, toolchains, containers, clusters, or model weights must be executed separately in an environment that meets those prerequisites; static review is never reported as a live execution pass. See the revised script at examples/22_linux_commands.sh.

We use Python to generate 2,000 lines of synthetic LLM gateway access logs (with a fixed random seed) and answer operational questions using only shell pipelines (Debian 13, GNU coreutils / gawk):

#!/usr/bin/env bash
# Practical Linux commands: answer operational questions from a synthetic LLM gateway access log.
set -euo pipefail
W=$(mktemp -d); cd "$W"
"${PY:-python3}" - <<'P'
import random; random.seed(6)
paths = ["/v1/chat"] * 7 + ["/v1/embed"] * 2 + ["/health"]
with open("gateway.log", "w") as f:
    for i in range(2000):
        p = random.choice(paths); code = random.choices([200, 429, 500, 401], [90, 6, 2, 2])[0]
        ms = int(random.lognormvariate(5.5 if p == "/v1/chat" else 3.5, 0.6)); user = f"u{random.randint(1, 40):02d}"
        f.write(f"2026-10-14T{8 + i * 12 // 2000:02d}:{(i * 7) % 60:02d}:00+08:00 {user} POST {p} {code} {ms}ms\n")
P
echo "== Quick inspection: head / wc"
head -3 gateway.log; wc -l gateway.log; ls -lh gateway.log | awk '{print "Size:", $5}'
echo "== (1) Status code distribution: awk column 5 -> sort -> uniq -c -> sort descending"
awk '{print $5}' gateway.log | sort | uniq -c | sort -rn
echo "== (2) Top 3 rate-limited (429) users"
grep ' 429 ' gateway.log | awk '{print $2}' | sort | uniq -c | sort -rn | head -3
echo "== (3) /v1/chat latency P50 / P95 / max (ms)"
grep ' /v1/chat ' gateway.log | awk '{gsub("ms","",$6); print $6}' | sort -n > lat.txt
n=$(wc -l < lat.txt); echo "Samples $n  P50=$(sed -n "$(((n*50+99)/100))p" lat.txt)  P95=$(sed -n "$(((n*95+99)/100))p" lat.txt)  max=$(tail -1 lat.txt)"
echo "== (4) Hourly 5xx error count"
awk '$5 ~ /^5/ {print substr($1, 12, 2) "h"}' gateway.log | sort | uniq -c | tr '\n' ' '; echo
echo "== (5) Live tailing: tail -f + grep --line-buffered (bounded to 1s with timeout)"
( sleep 0.3; echo "2026-10-14T21:00:00+08:00 u99 POST /v1/chat 500 9999ms" >> gateway.log ) &
timeout 1 tail -n 0 -f gateway.log | grep --line-buffered ' 500 ' || true
echo "== (6) find + xargs: locate logs larger than 10KB and compress them"
for i in 1 2 3; do head -c $((i * 5000)) /dev/urandom | base64 > "old-$i.log"; done
find . -name 'old-*.log' -size +10k -print0 | sort -z | xargs -0 -n1 gzip -v 2>&1 | sed 's/^/   /'
ls old-* | tr '\n' ' '; echo
echo "== (7) Permissions: when a script lacks execute permission"
printf '#!/bin/sh\necho Execution succeeded\n' > run.sh; ls -l run.sh | cut -d' ' -f1
./run.sh 2>&1 || true; chmod u+x run.sh; ls -l run.sh | cut -d' ' -f1; ./run.sh
rm -rf "$W"

Draft 1 Retained Output (historical environment record, not a re-run result from this batch):

== Quick inspection: head / wc
2026-10-14T08:00:00+08:00 u01 POST /health 200 32ms
2026-10-14T08:07:00+08:00 u24 POST /v1/chat 200 215ms
2026-10-14T08:14:00+08:00 u27 POST /v1/chat 200 75ms
2000 gateway.log
Size: 106K
== (1) Status code distribution: awk column 5 -> sort -> uniq -c -> sort descending
   1777 200
    128 429
     51 401
     44 500
== (2) Top 3 rate-limited (429) users
      8 u13
      7 u17
      6 u30
== (3) /v1/chat latency P50 / P95 / max (ms)
Samples 1405  P50=247  P95=617  max=2144
== (4) Hourly 5xx error count
      5 08h       2 09h       4 10h       4 11h       5 12h       3 13h       3 14h       5 15h       4 16h       1 17h       3 18h       5 19h 
== (5) Live tailing: tail -f + grep --line-buffered (bounded to 1s with timeout)
2026-10-14T21:00:00+08:00 u99 POST /v1/chat 500 9999ms
== (6) find + xargs: locate logs larger than 10KB and compress them
   ./old-2.log:	 23.9% -- replaced with ./old-2.log.gz
   ./old-3.log:	 24.0% -- replaced with ./old-3.log.gz
old-1.log old-2.log.gz old-3.log.gz 
== (7) Permissions: when a script lacks execute permission
-rw-r--r--
22_linux_commands.sh: line 34: ./run.sh: Permission denied
-rwxr--r--
Execution succeeded
  • (1) A single pipeline summarizes the HTTP status distribution: 1,777 responses with 200, 128 with 429 (rate-limited), 51 with 401, and 44 with 500.
  • (2) The most frequently rate-limited user is u13 (8 occurrences).
  • (3) Across 1,405 /v1/chat requests, P50 is 247 ms, P95 is 617 ms, and the maximum is 2,144 ms — averages hide long-tail latency, so always inspect percentiles. Using sort -n + sed -n 'Np' picks the N-th sorted line; Draft 1's line-index formula could evaluate to line 0 on very small sample counts, so Draft 2 switches to the nearest-rank ceiling formula ceil(p*n) clamped to at least line 1. Always state which percentile definition is being used.
  • (4) awk '$5 ~ /^5/' filters 5xx lines by regular expression and substr extracts the two-digit hour to count errors per hour.
  • (5) tail -f follows newly appended lines in real time; grep --line-buffered flushes every matching line immediately instead of waiting for the stdio buffer to fill up (which otherwise makes the pipeline appear stuck).
  • (6) find -size +10k selects only old-2.log and old-3.log (skipping old-1.log at ~6.7 KB) and compresses them via gzip; base64-encoded random bytes compress by only ~24%, whereas real text logs compress much further.
  • (7) A newly created file starts with mode -rw-r--r-- and fails with Permission denied when invoked directly; chmod u+x updates the mode to -rwxr--r-- so it can execute.

Common Pitfalls

  • "uniq removes all duplicate lines in a file": It only collapses adjacent identical lines, so you must pipe through sort first.
  • "sort orders numbers numerically by default": By default it sorts lexicographically as strings, placing 10 before 9; pass sort -n for numeric sorting.
  • "chmod 777 is an easy fix for permission errors": Granting read, write, and execute permissions to every local user creates a severe security exposure; grant only the minimum required mode bits (k6.sec.access-control).
  • "Recursive deletion is safe as long as the variable is quoted": An unset or empty variable can still resolve to the wrong path; set -u only catches unset variables (not empty strings), and double quotes only prevent word splitting and globbing. Always assert non-empty variables and verify the resolved canonical path — GNU rm's default root-directory protection does not protect other unintended target directories (see k6.ops.shell-script).

Relevance to AI Development

  • Everyday commands on GPU servers: nvidia-smi (VRAM usage and GPU utilization; not run in Draft 1's non-GPU environment), df -h (model caches frequently fill up disks), du -sh ~/.cache/huggingface, and free -h.
  • Quick triage of evaluation logs and API gateway traces: grep + awk handles most ad-hoc checks, while deeper multi-dimensional analysis can be loaded into SQL or pandas (k6.lang.sql).
  • When allowing an AI Agent to run shell commands, restrict it to an allowlist of read-only commands (ls, cat, grep) by default and require explicit confirmation for mutating operations (k6.sec.sandbox).

Self-Test & Answer

Question: Does quoting "$DIR/" make a recursive delete command safe?

Answer: No. Double quotes prevent word splitting and glob expansion, but they do not reject an empty string, the root directory /, or a path escaping the workspace; you must assert that the variable is non-empty, resolve and verify its canonical absolute path, and restrict operations to an allowed parent directory. Even though GNU rm protects / by default, it will not protect other unintended target directories.

Verification Sources & Corresponding Conclusions

  • GNU Coreutils Manual: adjacent deduplication in uniq, numeric sorting in sort -n, and root-directory protection in rm.
  • Bash set Builtin Manual: nounset (set -u) traps unset variables but does not trap variables assigned an empty string.

Unverified Scope & Follow-Up Checks

  • This GNU/Linux shell script was not executed directly on the Windows verification host in this batch; flag compatibility with BSD/macOS utilities requires separate testing.
  • Specific tool versions, timings, IP addresses, PIDs, and generated text from Draft 1 are not universal guarantees; record platform, dependencies, inputs, and current logs whenever reproducing results.

Example Execution Scope for This Batch

2026-10-15: Not re-run. Revised through documentation and code review against the listed references; the full example was not executed in this batch. The GNU/Linux shell script was not run on the Windows host, and BSD/macOS flag compatibility requires separate verification.

"Draft 1 Retained Output" preserves the original log text and is not newly generated by the Draft 2 code; its original conclusions should be read alongside the Draft 2 revisions and scope boundaries.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram