Shell Foundations
Quoting, pipes, status, toy files, loops, functions and safe automation patterns. POSIX-style syntax, Bash 3.2 and native Zsh are distinguished.
Audience: Beginners who can save plain text and run an installed command-line runtime.
Practice: 4 to 6 hours, at your own pace.
Runtime and boundaries: The terminal is an interface; sh, Bash and Zsh interpret command text. This pack tests macOS /bin/sh (selecting Bash 3.2.57), /bin/bash 3.2.57 and /bin/zsh 5.9. POSIX-style examples use a conservative shared syntax subset; Bash and Zsh examples name their extensions. Run scripts using the stated interpreter and a quoted filename; executable permission is unnecessary. A shebang documents the intended interpreter when a script is launched directly, but an explicit shell command chooses the interpreter regardless of the shebang.
Lessons
A shell is an interpreter, not a terminal
The terminal is an interface; sh, Bash and Zsh interpret command text. This pack tests macOS /bin/sh (selecting Bash 3.2.57), /bin/bash 3.2.57 and /bin/zsh 5.9. POSIX-style examples use a conservative shared syntax subset; Bash and Zsh examples name their extensions. Run scripts using the stated interpreter and a quoted filename; executable permission is unnecessary. A shebang documents the intended interpreter when a script is launched directly, but an explicit shell command chooses the interpreter regardless of the shebang.
Preserve data as arguments
Shell parsing, expansion and argument construction happen before a command runs. Use single quotes for fixed literal text and double quotes around variable expansions. Use "$@" to pass positional arguments individually. A wildcard stored in quoted data stays text. Avoid eval, command strings and sourcing untrusted files. printf with a fixed format is more predictable than treating user text as the format. Names with spaces, leading dashes or newlines need deliberate treatment; these exercises never use arguments as arbitrary file paths.
Make failures observable
An exit status of zero means success; nonzero meanings depend on the command. Inspect $? immediately or put the command in an if condition. && runs its right side after success; || runs its right side after failure. stderr is separate from stdout. Do not assume set -e provides complete error handling: context changes its behavior. Script checks here record stdout, stderr and exit status, including invalid inputs. A syntax check catches parse errors, not incorrect behavior.
Pipes need a status policy
A pipeline connects stdout to the next command. Without pipefail its status comes from the final command, so a failed earlier command can be hidden. Bash and Zsh support pipefail but differ in syntax and other behaviors. POSIX.1-2024 includes pipefail; older portability targets do not. This pack keeps the shared example at default behavior and labels dialect-specific checks. Avoid relying on a variable assigned inside a piped loop remaining visible outside it; shells differ. Feed a current-shell loop with redirection or a here-document.
File practice owns a small new directory
Redirection can overwrite files before a command runs. The file examples use macOS mktemp -d with a template under the current writable practice directory, umask 077 and fixed filenames inside the new directory. mktemp is a platform utility and not claimed as universal POSIX tooling. Only files created by the example are read. The scripts retain toy folders for inspection and contain no deletion commands. The harness removes only its own outer temporary directory. Never substitute a real document path.
Read and loop without losing text
IFS= read -r preserves leading/trailing whitespace and backslashes in a line. The examples use fixed newline-terminated text; a general arbitrary-file reader also needs a policy for a final line without a newline and cannot treat NUL-delimited data as ordinary shell strings. A quoted here-document delimiter suppresses expansion in its body. A for loop over positional parameters keeps argument boundaries. Bound while loops with validated inputs and test zero, maximum and invalid cases.
Functions and dialect boundaries
A shell function can communicate success through return and text through stdout. Prefer small functions with explicit input contracts. Bash 3.2 has zero-based indexed arrays but no associative arrays. Native Zsh arrays usually start at one, and its scalar splitting and glob defaults differ. Shell options can alter these behaviors, so the Zsh example uses emulate to establish native mode. The portable examples avoid arrays, [[ ... ]], local and shell-specific substitutions; passing three invocation modes across two implementations is evidence, not a standards certificate.
Build automation with a dry run first
Separate deciding from doing. Default to a printed plan, accept only documented modes, validate inputs before arithmetic or file access, and stop when creating the toy directory fails. The explicit write mode creates only a new fixed report. No cron jobs, network commands, permission changes or production integrations are included. Run tests with an empty controlled environment and a small PATH. Timeouts and a fresh directory bound trusted teaching examples; they are not a sandbox for arbitrary downloaded shell code.
Reference cards
Quoting: 'literal' / "$value"
Literal text / one expanded argument.
Arguments: "$@" / "$#"
Separate arguments / argument count.
Output: printf '%s\n' "$value"
Use a fixed format for text.
Status: if command; then ...; else ...; fi
Handle success and failure explicitly.
Status: $? / return / exit
Previous status / function outcome / process outcome.
Flow: && / ||
Continue after success / failure.
Streams: producer | consumer
Connect stdout; decide how failures propagate.
Streams: > / >> / 2>
Overwrite / append / redirect stderr; paths have effects.
Input: IFS= read -r line
Preserve whitespace and backslashes.
Flow: for item do ... done
Iterate over positional arguments.
Flow: case "$value" in ... esac
Match a small allowed input set.
Functions: name() { ...; }
Define a reusable shell operation.
Files: mktemp -d './atlas-shell.XXXXXX'
macOS utility: create a new local toy folder.
Bash: array=(...); "${array[0]}"
Bash indexed arrays start at zero.
Zsh: emulate -L zsh; "${array[1]}"
Native Zsh mode; first array element is one.
Safety: --dry-run / --write-toy
Example-specific allowlisted modes, not universal command flags.
Examples and practice
Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.
Shell 01 Preserve argument boundaries
Single quotes hold literal text; double quotes preserve an expanded value as one argument. Quoting data does not execute the characters stored in it. Use a fixed printf format. The empty argument is retained.
#!/bin/sh
topic='SQL and Shell'
literal='*.txt; $(not_a_command)'
printf 'Topic: %s\n' "$topic"
printf 'Literal: %s\n' "$literal"
set -- "$topic" "$literal" ''
printf 'Arguments: %s\n' "$#"
Expected:
Topic: SQL and Shell Literal: *.txt; $(not_a_command) Arguments: 3
Shell 02 Inspect exit status
Zero means success; nonzero denotes failure or another documented outcome. Save $? immediately. This example handles a known failure in if instead of relying on set -e, whose contextual rules can surprise learners.
#!/bin/sh
if false; then
printf '%s\n' 'Unexpected success'
else
result=$?
printf 'Handled status: %s\n' "$result"
fi
printf '%s\n' 'Continue deliberately'
Expected:
Handled status: 1 Continue deliberately
Shell 03 Transform a tiny stream
A pipe sends stdout to the next command. Sorting groups duplicates for uniq. With pipefail disabled, the final command determines the status; the failed first command is hidden here. Older POSIX shell targets do not promise pipefail; POSIX.1-2024 adds it, while installed-runtime support still needs checking.
#!/bin/sh
printf '%s\n' beta alpha beta | LC_ALL=C sort | uniq
false | cat
result=$?
printf 'Default pipeline status: %s\n' "$result"
Expected:
alpha beta Default pipeline status: 0
Shell 04 Write only a new toy file
macOS mktemp creates a new directory inside the writable practice folder. Its utility syntax is platform-specific. Fixed names inside that new directory cannot overwrite a previous document. IFS= read -r preserves spaces and backslashes. No deletion command is included; the test harness cleans its own outer directory.
#!/bin/sh
umask 077
toy_dir=$(mktemp -d './atlas-shell.XXXXXX') || exit 1
printf '%s\n' 'Read one example' 'Change one value' > "$toy_dir/notes.txt" || exit 1
count=0
while IFS= read -r line; do
count=$((count + 1))
printf 'Line %s: %s\n' "$count" "$line"
done < "$toy_dir/notes.txt"
printf 'Lines: %s\n' "$count"
printf '%s\n' 'Toy folder retained for inspection.'
Expected:
Line 1: Read one example Line 2: Change one value Lines: 2 Toy folder retained for inspection.
Shell 05 Loop over quoted values
The for loop without an in-list visits positional parameters as separate values. Arithmetic is used only on an internal counter. Do not feed untrusted strings into shell arithmetic or turn command text into code.
#!/bin/sh
set -- 'SQL basics' 'Shell basics' 'Python basics'
count=0
for topic do
count=$((count + 1))
printf '%s: %s\n' "$count" "$topic"
done
printf 'Visited: %s\n' "$count"
Expected:
1: SQL basics 2: Shell basics 3: Python basics Visited: 3
Shell 06 Validate with a function
The function returns a status, not a text result. The allowlist accepts a deliberately small ASCII token. It is a demonstration contract, not a universal filename sanitizer. No path is opened.
#!/bin/sh
valid_topic() {
case "$1" in
''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-]*) return 1 ;;
*) return 0 ;;
esac
}
for candidate in 'sql_01' 'two words' '' '../notes' 'é' 'Ä'; do
if valid_topic "$candidate"; then
printf 'Accepted: <%s>\n' "$candidate"
else
printf 'Rejected: <%s>\n' "$candidate"
fi
done
Expected:
Accepted: <sql_01> Rejected: <two words> Rejected: <> Rejected: <../notes> Rejected: <é> Rejected: <Ä>
Shell 07 Default to a dry run
No argument previews the operation. An explicit allowlisted mode creates one fixed report inside a new toy directory. Invalid modes fail before a write. This is a safe teaching pattern, not a scheduler or production automation system.
#!/bin/sh
mode=${1---dry-run}
case "$mode" in
--dry-run) printf '%s\n' 'Would create a new toy report.' ;;
--write-toy)
umask 077
toy_dir=$(mktemp -d './atlas-shell.XXXXXX') || exit 1
printf '%s\n' 'Study: SQL and Shell' > "$toy_dir/report.txt" || exit 1
printf '%s\n' 'Created one new toy report; folder retained.' ;;
*) printf '%s\n' 'Use --dry-run or --write-toy.' >&2; exit 2 ;;
esac
Expected:
Would create a new toy report.
Shell 08 Use Bash features explicitly
Run with Bash 3.2.57, not sh. Indexed arrays are zero-based, and quoted array expansion preserves each element. This old Bash lacks modern associative arrays. pipefail exposes the failed producer in this example.
#!/bin/bash
topics=('SQL basics' 'Shell basics')
printf 'First: %s\n' "${topics[0]}"
printf 'Count: %s\n' "${#topics[@]}"
for topic in "${topics[@]}"; do printf '<%s>\n' "$topic"; done
set -o pipefail
if false | cat; then
printf '%s\n' 'Unexpected success'
else
printf 'Bash pipeline status: %s\n' "$?"
fi
Expected:
First: SQL basics Count: 2 <SQL basics> <Shell basics> Bash pipeline status: 1
Shell 09 Use native Zsh deliberately
Native Zsh normally indexes arrays from one. emulate establishes the intended option mode. Default unquoted scalar splitting and unmatched glob behavior differ from Bash; these examples quote values and avoid ambiguous globbing. Use the named interpreter.
#!/bin/zsh
emulate -L zsh
topics=('SQL basics' 'Shell basics')
printf 'First: %s\n' "${topics[1]}"
printf 'Count: %s\n' "${#topics[@]}"
for topic in "${topics[@]}"; do printf '<%s>\n' "$topic"; done
setopt PIPE_FAIL
if false | cat; then
printf '%s\n' 'Unexpected success'
else
printf 'Zsh pipeline status: %s\n' "$?"
fi
Expected:
First: SQL basics Count: 2 <SQL basics> <Shell basics> Zsh pipeline status: 1
Shell Exercise A Keep every argument
No-argument mode supplies three toy values; explicit arguments are kept exactly as separate strings. The wildcard is printed literally.
#!/bin/sh
if [ "$#" -eq 0 ]; then set -- 'SQL basics' '*.txt' ''; fi
count=0
for item do
count=$((count + 1))
printf '%s: <%s>\n' "$count" "$item"
done
printf 'Arguments: %s\n' "$count"
Expected:
1: <SQL basics> 2: <*.txt> 3: <> Arguments: 3
Practice: Print each argument and a count, preserving spaces, empty strings and wildcard characters. With no arguments use the three toy values.
Shell Exercise B Count literal lines
A quoted here-document supplies fixed literal input. The loop stays in the current shell and preserves its counter. Empty means zero characters here; a whitespace-only line would count.
#!/bin/sh
count=0
while IFS= read -r line; do
case "$line" in '') continue ;; esac
count=$((count + 1))
printf '<%s>\n' "$line"
done <<'LESSON_TEXT'
SQL basics
keep spaces
literal\backslash
LESSON_TEXT
printf 'Nonempty lines: %s\n' "$count"
Expected:
<SQL basics> < keep spaces > <literal\backslash> Nonempty lines: 3
Practice: Count nonempty lines from literal toy input while preserving leading/trailing spaces and backslashes. Keep the final count outside the loop.
Shell Exercise C Bound a small loop
An exact allowlist bounds the loop before numeric comparison. It rejects negative, large, empty and expression-shaped inputs. This avoids arithmetic interpretation of arbitrary text.
#!/bin/sh
requested=${1-3}
case "$requested" in
0|1|2|3|4|5) ;;
*) printf '%s\n' 'Use one digit from 0 to 5.' >&2; exit 2 ;;
esac
count=0
while [ "$count" -lt "$requested" ]; do
count=$((count + 1))
printf 'Practice %s\n' "$count"
done
printf 'Completed: %s\n' "$count"
Expected:
Practice 1 Practice 2 Practice 3 Completed: 3
Practice: Accept only one digit from 0 to 5, default to 3, print that many steps and a summary. Reject every other argument before the loop.
Prompt templates
These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.
Build an example
Create an original {language} example for {goal}. Runtime: {runtime}. Constraints: {constraints}. State the dialect, input contract, complete files and exact expected output. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Debug a failure
Debug this {language} behavior for {goal} under {runtime}. Constraints: {constraints}. Ask for the smallest reproducer, explain the failure, and suggest a focused correction with a regression case. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Test the contract
Design tests for {goal} in {language} under {runtime}. Constraints: {constraints}. Cover empty input, boundaries, invalid values, status and side effects; provide expected outputs and an isolated test procedure. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Refactor with evidence
Refactor {goal} in {language} for clarity under {runtime}. Constraints: {constraints}. Preserve behavior, identify dialect assumptions and compare results before and after. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Document a local recipe
Document {goal} in {language} under {runtime}. Constraints: {constraints}. Explain inputs, exact invocation, outputs, failure handling, effects and limitations. Label shell dialect details clearly. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Review safety and portability
Review {goal} in {language} for shell dialect portability and safety under {runtime}. Constraints: {constraints}. Check quoting or binding boundaries, unintended effects and failure behavior; distinguish observed facts from assumptions. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.Further reading
- Installed Bash 3.2 manual — Quoting, positional parameters, loops, functions, arrays, redirections and pipeline status. Read from /usr/share/man/man1/bash.1.
- Installed macOS sh manual — macOS sh selects an implementation; this host selects /bin/bash 3.2.57.
- Installed macOS mktemp manual — Create a unique directory using a template; platform utility, not a portable POSIX utility claim.
- Zsh shell grammar — Pipelines, conditionals, quoting and exit status.
- Zsh parameters — Native array indexing and parameter behavior.
- Zsh options — Native options, SH_WORD_SPLIT and pipeline behavior.
Download the offline edition
Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON
Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.
Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.
Evidence and limits
Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.
The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.
Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.