Computing Foundations › The Command Line › Day 12

Day 12: Shell Scripting: Variables, Loops, and Conditionals

Day 12 of 365 — Shell Scripting: Variables, Loops, and Conditionals

After this lesson you will be able to turn a sequence of commands into a reliable shell script — using variables, quoting, command substitution, arguments, conditionals, loops, and functions under strict mode — so your work runs the same way every time and is genuinely reproducible.

Course
Computing Foundations
Category
The Command Line
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-012-shell-scripting-variables-loops-and-conditionals

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-012-shell-scripting-variables-loops-and-conditionals
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language


Historical background


What it is — and what it is not

It is:

It is not:


Why it was created and what problems it solves


How it works

From a command to a script

#!/usr/bin/env bash
set -euo pipefail

echo "Starting up"
echo "Today is $(date '+%Y-%m-%d')"

Diagram: running a script with bash compared with running it directly

Variables and quoting

Diagram: an unquoted variable compared with a quoted one

name="Ada"
greeting="Hello, ${name}"
echo "${greeting}"

Command substitution

today="$(date '+%Y-%m-%d')"
count="$(ls -1 | wc -l)"

Reading arguments

target="${1:-.}"
echo "Working on: ${target}, with $# argument(s)"

Conditionals

Diagram: how exit codes drive conditionals and pipelines

if [[ -d "${target}" ]]; then
  echo "It is a directory"
else
  echo "No such directory: ${target}"
fi

Diagram: string test operators compared with numeric ones

Loops and functions

for f in *.txt; do
  echo "Found: ${f}"
done

while read -r line; do
  echo "Line: ${line}"
done < notes.txt

log() {
  local msg="$*"
  echo "[$(date '+%H:%M:%S')] ${msg}"
}

Diagram: the anatomy of a shell script, labelling the shebang, strict-mode line, variables, a function, a conditional, and a loop

Strict mode: set -euo pipefail

Diagram: the three protections in shell strict mode

Asking a question

read -r -p "Delete these files? [y/N] " answer
[[ "${answer}" == "y" ]] && echo "Deleting..." || echo "Cancelled"

Flowchart: an if/else decision and a for loop drawn as a control-flow diagram


An everyday analogy

Diagram: how a trap guarantees cleanup on exit

A recipe card.

The kitchenThe script
The recipe cardThe script file
”Serves 4” at the topThe shebang and strict mode
Ingredients listVariables
”If the sauce is thin, simmer”A conditional
”Repeat for each portion”A loop
”Make the roux (see page 12)“A function
Taste before servingChecking exit codes

Examples in practice

Diagram: a script failing with and without set -euo pipefail


Implications: security, privacy, performance, scalability, and cost


Alternatives: free, open source, and commercial

Diagram: the point at which a shell script should become a Python program

ToolTypeWhen to use it instead
bashFree, built inGlue, automation, anything under ~100 lines
POSIX shFree, built inMaximum portability, minimum features
PythonFree, open sourceData structures, real error handling, tests
makeFree, built inDependency graphs — rebuild only what changed
justFree, open sourceA friendlier task runner, without make’s traps
shellcheckFree, open sourceNot an alternative — a linter you should always run

TermWhat it actually is
ScriptA file of commands for an interpreter
ShebangThe first line naming that interpreter
Exit codeThe integer a command returns; 0 is success
Positional parameter$1, $2 — an argument by position
Command substitution$(...) — a command’s output used as a value
Strict modeset -euo pipefail, the safety line

When to use it — and when not to

Diagram: a for loop compared with a while loop


The AI connection


Knowledge check

quiz:
  question: "A script runs `download_data | unpack` and reports success, but the output directory is empty. Which strict-mode option would have caught this?"
  options:
    - "-o pipefail, because a pipeline's exit code otherwise comes only from its last command"
    - "-e, because the script would have exited at the first failing command"
    - "-u, because the output path variable was never set"
    - "-x, because tracing would have shown which command failed"
  answer_index: 0
  explanation: "Without pipefail, a pipeline reports whatever its final command returned. unpack succeeded at unpacking nothing, so the pipeline looked fine even though the download had already failed."

Hands-on exercise

Write a script that takes an argument, loops over files, and fails loudly. Worked through fully in the Day 12 lab directory.

What you are doingCommand or line
Start the file properly#!/usr/bin/env bash then set -euo pipefail
Take an argument with a defaulttarget="${1:-.}"
Guard against a bad input[[ -d "$target" ]] || { echo "no such dir" >&2; exit 1; }
Loop over matching filesfor f in "$target"/*.txt; do ... done
Capture a valuecount="$(ls -1 "$target" | wc -l)"
Run itchmod +x tool.sh then ./tool.sh reports
Lint itshellcheck tool.sh

Expected output

[14:02:11] Working on: reports
[14:02:11] Found: reports/summary.txt
[14:02:11] 3 entries
./tool.sh: line 9: nosuchcmd: command not found

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What is the purpose of the first line `#!/usr/bin/env bash` in a script?

  1. It is a comment the shell ignores completely
  2. It imports a library of extra shell commands
  3. It is the shebang: run this file with bash
  4. It makes the file executable automatically
Show answer

Answer: C. It is the shebang: run this file with bash

The shebang `#!` followed by an interpreter path tells the system which program should run the file. Using `/usr/bin/env bash` finds bash on the user's PATH, which is more portable than a hard-coded path. It does not, by itself, set the executable permission bit.

Q2. Why should you almost always quote a variable expansion, writing `rm "$file"` instead of `rm $file`?

  1. Quoting makes the script run faster
  2. Quotes convert the value to uppercase
  3. Unquoted variables are a syntax error in bash
  4. Unquoted values are word-split and globbed
Show answer

Answer: D. Unquoted values are word-split and globbed

Without quotes the shell splits the value at spaces and expands glob characters like `*`. A value such as `my notes.txt` becomes two arguments, and `*` becomes every file in the directory. Quoting passes the value through as a single, literal argument.

Q3. What does `set -euo pipefail` do?

  1. Exit on error, on unset variables, and on pipeline failure
  2. Turns on verbose logging of every command
  3. Disables all error checking so the script never stops
  4. Sets three environment variables named e, u, and o
Show answer

Answer: A. Exit on error, on unset variables, and on pipeline failure

`-e` exits on the first command that fails, `-u` treats use of an unset variable as an error (catching typos), and `-o pipefail` makes a pipeline report failure if any command in it fails, not just the last. Together they turn a forgiving shell into a strict one that stops when something is wrong.

Q4. What does command substitution `$(date +%Y)` produce?

  1. The literal text "date +%Y"
  2. The output of `date +%Y`, substituted in place
  3. An error, because commands cannot appear inside scripts
  4. The exit code of the date command
Show answer

Answer: B. The output of `date +%Y`, substituted in place

Command substitution runs the command inside `$(...)`, captures what it prints, trims the trailing newline, and substitutes the result as a value. It lets a script react to real information rather than a hard-coded guess.

Q5. A script uses `if [ $count = 5 ]` to compare a number and behaves oddly. What is the correct integer comparison?

  1. `if [ $count == 5 ]`
  2. `if [ $count -is 5 ]`
  3. `if [ $count -eq 5 ]`
  4. `if ( count = 5 )`
Show answer

Answer: C. `if [ $count -eq 5 ]`

In test expressions, `=` compares strings while `-eq`, `-gt`, `-lt`, and similar operators compare integers. Use `[ "$count" -eq 5 ]` for numbers. Quoting the variable also avoids an error when the value is empty.

Q6. Which loop is the natural choice for reading a file one line at a time?

  1. A `for` loop over `*.txt`
  2. Recursion, since shells have no loops
  3. A `case` statement
  4. A `while read -r line` loop
Show answer

Answer: D. A `while read -r line` loop

A `while read -r line` loop reading from a redirected file processes one line per iteration and stops at end of file, which is exactly the "repeat while the command succeeds" pattern `while` is built for. A `for` loop suits iterating over a known list such as files matching a pattern.

Q7. What is the difference between `$1` and `$@` in a script?

  1. `$1` is the first argument; `$@` is all of them
  2. They are identical
  3. `$1` is the exit code; `$@` is the script name
  4. `$1` is the number of arguments; `$@` is the first one
Show answer

Answer: A. `$1` is the first argument; `$@` is all of them

`$1` is the first argument passed to the script, `$2` the second, and so on. `$@` expands to all the arguments (quote it as `"$@"` to keep each one intact), and `$#` is the count of arguments.

Q8. Why is `[[ ... ]]` generally preferred over `[ ... ]` in a bash script?

  1. It runs on every shell including minimal POSIX sh
  2. It is a bash built-in that does not word-split and supports patterns
  3. It is required for the shebang to work
  4. It automatically quotes every variable for you regardless of shell
Show answer

Answer: B. It is a bash built-in that does not word-split and supports patterns

`[[ ]]` is a bash keyword that avoids the word-splitting and globbing pitfalls of the older `[` command and adds pattern matching and logical operators inside the brackets. Use `[ ]` only when a script must run under plain POSIX `sh`, which lacks `[[ ]]`.

Glossary

shebang
The `#!` characters on a script's first line, followed by the path to an interpreter (e.g. `#!/usr/bin/env bash`), telling the system which program should run the file.
variable
A named holder for a value in a script, assigned with `name=value` (no spaces around `=`) and read with `$name` or `${name}`.
quoting
Wrapping a value in double quotes, as in `"$file"`, to stop the shell from word-splitting it at spaces and expanding glob characters like `*` — the single most important habit for correct scripts.
command substitution
The `$(command)` form, which runs a command and replaces itself with that command's captured output, letting a script use real results as values.
exit code
The integer a command returns when it finishes — `0` for success and non-zero for failure — which conditionals and loops branch on.
conditional
An `if`/`then`/`else` construct that runs commands based on whether a test succeeds, where the test is any command judged by its exit code.
loop
A construct that repeats a block of commands: `for` iterates over a known list, while `while` (and `until`) repeats based on a command's exit code.
function
A named, reusable group of commands defined with `name() { ... }` and called like any command; inside it, `$1` and `$2` are the arguments passed to the function.
positional parameter
The numbered inputs a script receives on the command line — `$1`, `$2`, and so on — with `$#` giving their count and `$@` expanding to all of them.
test command
The `[ ... ]` (also spelled `test`) or the bash-only `[[ ... ]]` construct that evaluates a condition, such as `-d` for "is a directory", and returns an exit code.
ShellCheck
A free, open-source static analyzer (linter) for shell scripts that flags bugs like unquoted variables and misused test brackets before the script is ever run.
set -e
A shell option (part of `set -euo pipefail`) that makes a script exit immediately when any command fails, instead of blindly continuing after an error.
strict mode
The convention of putting `set -euo pipefail` near the top of a script so it stops on errors, errors on unset variables, and detects failures anywhere in a pipeline.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.