diff --git a/.agents/skills/add-concept-exercise/SKILL.md b/.agents/skills/add-concept-exercise/SKILL.md new file mode 100644 index 00000000..f4a92003 --- /dev/null +++ b/.agents/skills/add-concept-exercise/SKILL.md @@ -0,0 +1,222 @@ +--- +name: add-concept-exercise +description: Scaffold a complete concept exercise for the Exercism Bash track, given a concept slug. Creates the exercise directory under exercises/concept/, all student-facing and meta files, and the track-level config.json entry, then validates everything. +--- + +# Add a Concept Exercise (Bash track) + +This track has concept _documentation_ (`concepts//`) but the learning syllabus is incomplete: there are few or no concept _exercises_ (`exercises/concept//`). +This skill walks through adding one correctly. + +## Inputs + +Collect these before starting (ask the user for anything missing): + +- **concept slug** (required): one of the slugs in `concepts/` and in the top-level `config.json` `concepts` array, e.g. `variables`, `arrays`, `conditionals`, `looping`, `arithmetic`, `quoting`, `pipelines`, `functions`, `redirection`, `heredocs`, `commands-and-arguments`, `more-arrays`. +- **exercise slug** (required): kebab-case, matching `[a-z0-9-]+`, named after the **story/theme**, NOT after the concept (`lasagna`, `bird-count`, `log-line-parser` are good; `floating-point-numbers` is not). +- **exercise name** (required): display name, e.g. `Lucian's Luscious Lasagna`. +- **story/theme**: a short narrative framing the tasks. +- **author handle**: the user's GitHub/Exercism handle for `.meta/config.json`. + +Prefer reusing an existing Exercism story when one fits the concept: it comes with a ready-made exercise icon and cross-track familiarity. +The canonical story list is at . +A novel story works too, but the exercise will need an icon eventually (see "Follow-ups" below). + +## Prerequisites: where the exercise fits in the syllabus + +`docs/SYLLABUS.md` defines the intended concept ordering. +The exercise's `prerequisites` are the concepts the student must already have unlocked before attempting this one. +Read `docs/SYLLABUS.md` and the target concept's `concepts//introduction.md` and `about.md` before writing anything. + +## Step 1: Scaffold the exercise directory + +Create `exercises/concept//` (kebab-case directory) with these files. +Filenames use snake_case derived from the slug (e.g. `bird-count` → `bird_count.sh` / `bird_count.bats`). + +### `.sh` — student stub + +- Shebang `#!/usr/bin/env bash`. +- Guiding comments only: describe the input, the expected output, and hints about structure. + NEVER include a working solution in the stub. +- Match the tone of existing stubs, e.g. `exercises/practice/two-fer/two_fer.sh`. + +### `.bats` — tests + +- Start with `#!/usr/bin/env bats` and `load bats-extra`. +- **Concept exercise tests have NO skip directives.** + The `[[ $BATS_RUN_SKIPPED == "true" ]] || skip` convention applies only to practice exercises. + `bin/validate_one_exercise` enforces this split automatically (it only checks skips outside `exercises/concept/`). +- Use `test_snake_case_names() { # @test` and keep test order aligned with the numbered tasks in `.docs/instructions.md`. +- Use `run bash .sh ...` and the `assert_success` / `assert_failure` / `assert_output` family from `bats-extra.bash`. +- Tests are hand-written: concept exercises have no `.meta/template.j2` or `.meta/tests.toml`, and `bin/generate_tests` does not apply. + +### `bats-extra.bash` — vendored assertion library + +Copy it verbatim from any practice exercise, e.g.: + +```bash +cp exercises/practice/two-fer/bats-extra.bash exercises/concept// +``` + +Do not modify it. + +### `.docs/introduction.md` — concept intro for this exercise + +- Introduces the concept(s) the exercise teaches, as the student will see it alongside the exercise. +- Derive it from `concepts//introduction.md`, but condense: cover only what the tasks require. + It is fine to copy sections verbatim. + +### `.docs/instructions.md` — story and tasks + +- Open with the story, then numbered tasks (`## 1. ...`, `## 2. ...`). +- Each task states exactly what the program must output for given inputs; include example invocations (`bash .sh ...`) and expected output where it helps. +- See `../jq` track concept exercises (e.g. `exercises/concept/lasagna/.docs/instructions.md`) for the house style. + +### `.docs/hints.md` — hints + +- A `## General` section, then one section per task mirroring the instruction headings. +- Link to relevant reference docs (GNU bash manual sections, the track's own concept pages). + +### `.meta/config.json` — exercise metadata + +```json +{ + "authors": [""], + "files": { + "solution": [".sh"], + "test": [".bats"], + "exemplar": [".meta/exemplar.sh"], + "invalidator": ["bats-extra.bash"] + }, + "blurb": "" +} +``` + +Note the key is `exemplar`, not `example` — concept exercises use an _exemplar_ solution, and the track-level `config.json` `files` section already maps `"exemplar": [".meta/exemplar.sh"]`. + +### `.meta/exemplar.sh` — reference solution + +- The reference solution; must pass every test in `.bats`. +- Must be ShellCheck-clean (`bin/lint` covers exercise shell files). +- Follow POLICIES.md (Google Shell Style Guide) and the track's bash conventions: quote expansions, use `local` in functions, prefer builtins where appropriate. +- Exemplars should model good style: this is what "done well" looks like. + +### `.meta/design.md` — design document + +Use this structure (adapted from the jq track's concept exercises): + +```markdown +# Design + +## Goal + +The goal of this exercise is to introduce . + +## Learning objectives + +- + +## Out of scope + +- + +## Concepts + +The Concepts this exercise unlocks are: + +- `` + +## Prerequisites + +- `` +``` + +Every learning objective must be addressable in the exercise itself. +For each objective, be able to point to where the student learns it (`.docs/introduction.md`, stub comments) and, where practical, where the student practices it (a task in `.docs/instructions.md` and its tests). +If an objective is neither taught nor exercised, reword the objective or change the exercise. + +## Step 2: Register the exercise in the track config + +Edit the top-level `config.json`: + +1. If there is no `exercises.concept` key yet, add it; otherwise append to it. + Concept exercises are listed in syllabus order (prerequisites first): + + ```json + "concept": [ + { + "slug": "", + "name": "", + "uuid": "", + "concepts": [""], + "prerequisites": ["", "..."], + "status": "wip" + } + ] + ``` + +2. Generate the uuid with `uuidgen | tr 'A-F' 'a-f'` (or `bin/configlet uuid` if configlet is available). + Never reuse or invent non-random uuids. +3. New exercises start as `"status": "wip"`. + Flip to `"beta"` (and later `"active"`) once reviewed. +4. `status.concept_exercises` at the top level stays `false` until the first concept exercise ships as `beta`/`active`; set it to `true` at that point. +5. Do not touch `exercises.practice` or `exercises.foregone`. +6. Preserve the existing JSON formatting (2-space indent) and LF line endings. + +## Step 3: Validate + +Run these in order and report the results honestly: + +1. **Learning objectives coverage review (manual):** + For each learning objective in `.meta/design.md`, name the file(s) that address it (introduction, instructions task, hints, stub, or tests). + Confirm no task requires knowledge listed under "Out of scope". + Resolve any objective that is neither taught nor exercised before proceeding. + +2. **Exercise tests against the exemplar:** + + ```bash + bin/validate_one_exercise exercises/concept/ + ``` + + This copies the exemplar over the stub name in a temp dir and runs the bats suite. + It must pass all tests with zero skips. + +3. **ShellCheck:** + + ```bash + bin/lint + ``` + + Note: `bin/lint` derives its file list from `config.json` and skips exercises with `"status": "wip"`, so it will NOT cover a brand-new exercise. + Also run shellcheck directly on the new files: + + ```bash + shellcheck exercises/concept//.sh \ + exercises/concept//.meta/exemplar.sh + ``` + +4. **Configlet** (metadata/config consistency): + + ```bash + bin/configlet lint + ``` + + If `bin/configlet` does not exist, run `bin/fetch-configlet` first. + If configlet cannot be fetched or run, say so — never claim it passed. + +5. **Review the diff:** `git status` and `git diff` — changes should be limited to the new exercise directory and the `exercises.concept` / `status` entries in `config.json`. + +## Gotchas + +- Bats `run` merges stdout and stderr into `$output`: exemplar code must not print diagnostics. + While debugging tests, write to fd 3 (`printf '...\n' >&3`) and remove it before finishing. +- Concept exercises have no skip directives and no `tests.toml`/`template.j2`. +- Keep LF line endings everywhere. +- The stub must remain a stub — do not let exemplar code leak into it. +- If debugging output is added to track tooling (scripts under `bin/`), write it to stderr and remove it before finishing. + +## Follow-ups (mention these to the user; do only if asked) + +- Update `docs/SYLLABUS.md` to link the new exercise. +- If the story is novel (not forked from another track), the exercise needs an icon: open an issue in the exercism/website-icons repository. +- When the exercise (and enough of the syllabus) is ready for students, change its status from `wip` to `beta` and set top-level `status.concept_exercises` to `true`. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..fdc1f1a1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,122 @@ +# Exercism Bash Track Agent Instructions + +## Scope + +This repository maintains the Exercism Bash track: exercises, tests, example solutions, documentation, configuration, and track tooling. + +Students solve exercises on the Exercism website or in their own Exercism CLI workspaces. +Do not treat this repository as a student workspace or fill in student stubs with completed solutions. + +Follow `POLICIES.md`. +Keep changes scoped to the requested exercise or track component, preserve existing work, and avoid unrelated formatting or generated-file churn. + +## Exercise layout + +Practice exercises live in `exercises/practice//`. +Read each exercise's `.meta/config.json` to confirm its configured filenames. + +- `.sh`: student-facing stub; normally remains incomplete. +- `.bats`: tests delivered to students. +- `.meta/example.sh`: reference solution; must pass all tests. +- `.meta/template.j2`: test-generation template, when present. +- `.meta/tests.toml`: canonical test selection and metadata. +- `.meta/config.json`: exercise metadata and file mappings. +- `.docs/`: student-facing instructions and documentation. +- `bats-extra.bash`: vendored Bats support/assertion library. + +## Maintaining exercises + +- Keep instructions, tests, example solutions, stubs, and metadata consistent. +- When tests change, ensure `.meta/example.sh` demonstrates the intended behavior and passes the complete test suite. +- Preserve the student-facing stub's intended level of guidance; do not turn it into another example solution. +- For exercises with `.meta/template.j2`, treat the `.bats` file as generated. + Change the template or shared `bin/generator_macros.j2`, then regenerate rather than making generated edits that would be overwritten. +- Use canonical data from `problem-specifications` and `.meta/tests.toml`. + Do not invent canonical UUIDs or silently omit canonical cases. +- Preserve the skip convention: the first skip directive is commented out and later tests have active directives. + Validation uses `BATS_RUN_SKIPPED=true` to run all tests. +- Do not modify `bats-extra.bash` unless updating the vendored library is part of the task. + +Regenerate tests only for affected exercises when possible: + +```bash +bin/generate_tests two-fer +``` + +The generator requires Python 3.11 or newer, Jinja2, and the cached problem-specifications repository. +Report missing prerequisites rather than claiming generation succeeded. + +## Skills + +Task-specific skills live in `.agents/skills/`. +Use `.agents/skills/add-concept-exercise/SKILL.md` when adding a concept exercise for one of the concepts documented in `concepts/`. + +## Bash conventions + +- Target Bash, not POSIX `sh`; POSIX compatibility is not required. +- Follow `POLICIES.md`, including the Google Shell Style Guide, while matching the surrounding file's established style. +- Use `#!/usr/bin/env bash` where a shebang is needed. +- Quote expansions unless splitting or globbing is explicitly intended. + Correctly handle whitespace, empty strings, and glob characters. +- Prefer clear Bash conditionals, arrays, functions, and builtins where appropriate. + Use `local` for function-local variables. +- Ensure exercise programs produce exactly the output and exit status expected by their tests. + Bats `run` collects both stdout and stderr in `$output`, so writing diagnostics to either stream can break `assert_output`, `refute_output`, and related assertions. +- When diagnostic output is needed while validating an exercise, write it to file descriptor 3 so Bats does not include it in `$output`: + + ```bash + printf 'debug: value=%q\n' "$value" >&3 + ``` + +- In standalone track-maintenance scripts, such as those under `bin/` or `.github/scripts/`, write diagnostics to stderr instead: + + ```bash + printf 'error: invalid exercise configuration\n' >&2 + ``` + +- Remove temporary diagnostic output before finishing unless the user explicitly asks to retain it. +- Avoid unnecessary dependencies and unrelated rewrites. +- Preserve LF line endings. + +## Validation + +After changing an exercise's tests, template, or example solution, run: + +```bash +bin/validate_one_exercise exercises/practice/two-fer +``` + +This script copies the example solution, tests, `bats-extra.bash`, and any configured editor files into a temporary directory, then runs all Bats tests there against the example. +The temporary directory is removed on exit. +It validates the **example solution**, not student code. +The exercise directory, including the student-facing stub, is never modified, so uncommitted changes to it are safe. + +Pass `-D` to run the tests inside the `exercism/bash-test-runner` Docker image instead of locally: + +```bash +bin/validate_one_exercise -D exercises/practice/two-fer +``` + +For broad exercise changes, validate all exercises: + +```bash +bin/validate_exercises +``` + +Run ShellCheck over active exercise shell files with: + +```bash +bin/lint +``` + +For configuration or metadata changes, also run: + +```bash +bin/configlet lint +``` + +Use `bin/fetch-configlet` only when configlet is needed and fetching it is acceptable. +Do not install global dependencies without approval. + +Before finishing, inspect the relevant diff and working-tree status. +Report which checks ran and any that could not run; never claim unrun checks passed. diff --git a/POLICIES.md b/POLICIES.md index cd0cf3f2..9a742074 100644 --- a/POLICIES.md +++ b/POLICIES.md @@ -26,6 +26,12 @@ This is most important for the tests, since they are delivered as a product, and [bash style guide]: https://google.github.io/styleguide/shellguide.html +### Markdown style + +Markdown documents in this repository should use "ventilated prose": one sentence per line. +This keeps diffs focused on the sentences that actually changed, which makes code review easier. +Additionally, ensure that both headers and lists have a blank line before and after them. + ### Prefer standard Bash over POSIX compliance When submitting or updating exercises, POSIX compliance is not required. diff --git a/concepts/commands-and-arguments/about.md b/concepts/commands-and-arguments/about.md index ecac6bfa..a8051ced 100644 --- a/concepts/commands-and-arguments/about.md +++ b/concepts/commands-and-arguments/about.md @@ -46,7 +46,7 @@ All the remaining words become _arguments_ to that command (options, filenames, In the examples below, we'll show you some interactive commands that you can run. * The `#` character starts a _comment_. - Any words following the comment comment are ignored by the shell; the comment is meant only for reading. + Any words following the `#` are ignored by the shell; the comment is meant only for reading. * The `$` character denotes a shell prompt. If you're copying the command, do not include the prompt. ~~~~ @@ -79,6 +79,8 @@ This is a test. ``` `echo` is a command that prints its arguments to standard output (which in our case is the terminal). +It separates the arguments with a single space and finishes the output with a newline. +Called without any arguments, `echo` prints a blank line. Bash splits the command into five words, and invokes the `echo` command with four arguments. The extra spaces in the second example make no difference. `echo` does not know how spaces were originally between the words. @@ -195,7 +197,7 @@ The directories are searched in order, from left to right, to see whether they c If the executable is outside a known path, the executable's file path will need to be specified. For the `myprogram` executable in the current directory, use `./myprogram`; if it's in the directory `/opt/somedirectory`, use `/opt/somedirectory/myprogram`. -Tip: The `type` command can be used to get detalis about the command: +Tip: The `type` command can be used to get details about the command: ```bash $ type rm @@ -220,25 +222,26 @@ Making a script is easy. Begin by making a new file, and put this on the first line: ```bash -#!/bin/bash +#!/usr/bin/env bash ``` This line is called an _interpreter directive_ (it is also called a _hashbang_ or **_shebang_**). -It specifies that `/bin/bash` is to be used as the interpreter when the file is used as the executable in a command. +It specifies that `bash` is to be used as the interpreter when the file is used as the executable in a command. When the OS's kernel executes a _non-binary file_, it reads the first line of the file. If the line begins with `#!`, the kernel uses the line to determine the interpreter to relay the file to. (There are other valid ways to do this as well, see below.) The `#!` must be at the very start of the file, with no spaces or blank lines before it. Our script's commands will appear on separate lines below this. -Tip: Instead of `#!/bin/bash` , you could use +Tip: Instead of `#!/usr/bin/env bash`, you could use ```bash -#!/usr/bin/env bash +#!/bin/bash ``` -`env` searches `$PATH` for the executable named by its first argument (in this case, "bash"). -For a more detailed explanation of this technique and how it differs from plain ol' `#!/bin/bash`, see [this question in StackOverflow][env bash]. +This hard-codes the path to the `bash` executable. +`env` instead searches `$PATH` for the executable named by its first argument (in this case, "bash"), which is more portable. +For a more detailed explanation of the `env` technique and how it differs from plain ol' `#!/bin/bash`, see [this question in StackOverflow][env bash]. Please do not be fooled by scripts or examples on the Internet that use `/bin/sh` as the interpreter. **`sh` is not `bash`!** diff --git a/concepts/commands-and-arguments/introduction.md b/concepts/commands-and-arguments/introduction.md index 7fa642b6..9eae2b44 100644 --- a/concepts/commands-and-arguments/introduction.md +++ b/concepts/commands-and-arguments/introduction.md @@ -1,282 +1,151 @@ -# Introduction to Shell Fundamentals - -## Shells - -A _shell_ is a program that allows you to enter commands to interact with the operating system. -Shells can be graphical; your desktop environment that you use with a mouse or trackpad is a shell. -We will focus on command-line interfaces, where you type commands and the results are (usually) printed in your terminal. - -There are many different command-line shells. -Windows offers **cmd** and **powershell**. -Mac and Linux offer "Unix shells", of which there are many. -The default shell for Mac is **zsh**. -**csh** is a legacy shell with C-like syntax. -**bash** is one of the most popular shells, particularly on Linux. - -One of the very earliest shells is the Bourne shell, **sh**. -In time, this shell became [standardized][posix] to be provided on every Unix-like system. -Many shells are based on the Bourne shell, often providing additional interactive or programming functionality. - -**Bash** is based on the Bourne shell. -That's why it is called the "**B**ourne-**a**gain **sh**ell". -It is the default shell on many Linux systems. -Bash provides many facilities that make it an enjoyable interactive shell, including: - -* a fully customizable prompt, -* the ability to recall and modify commands from history, -* the ability to manipulate running processes, -* aliases that can reduce typing, -* and more. +# Introduction to Commands and Arguments This track is not about how to use bash as an interactive shell. It is about learning to write programs using bash. -The emphasis will be on using _just_ bash to solve problems, although there are no restrictions on calling out to external tools. - -## Bash Fundamentals: Commands and Arguments -Bash reads commands from its input (which is usually either a terminal or a file). -Each line of input that it reads is treated as a _command_ — an instruction to be carried out. -(There are a few advanced cases, such as commands that span multiple lines, that will be discussed later.) +A Bash program, or _script_, is a sequence of commands stored in a file. +Bash reads the file and executes the commands in order. -Bash divides each line into **words** that are demarcated by a whitespace character (spaces and tabs). -The first word of the line is the name of the _command_ to be executed. -All the remaining words become _arguments_ to that command (options, filenames, etc.). +## The shebang -~~~~exercism/note -In the examples below, we'll show you some interactive commands that you can run. - -* The `#` character starts a _comment_. - Any words following the comment comment are ignored by the shell; the comment is meant only for reading. -* The `$` character denotes a shell prompt. - If you're copying the command, do not include the prompt. -~~~~ +The first line of a script is usually an _interpreter directive_, also known as a _hashbang_ or _shebang_: ```bash -# Note: It is always a good idea to run `ls` before `rm` -# to make sure you know what you are deleting. - -$ rm * # Remove all files in the current directory. - # Make sure you run this in a temp directory or you can lose files! -$ ls # List files in the current directory (no output, no files). -$ touch a b c # Create files 'a', 'b' and 'c'. -$ ls # List files again; this time the outputs: 'a', 'b' and 'c'. -a b c +#!/usr/bin/env bash ``` -`rm` is an application that removes the files given to it. -`*` is a [glob][glob] character, a "wildcard" pattern that matches all files in the current directory. -We will talk more about globs later. - -Did you notice that there are several spaces between `a` and `b`, and only one between `b` and `c`? -The amount of whitespace between arguments does not matter! -For example: - -```bash -$ echo This is a test. -This is a test. -$ echo This is a test. -This is a test. -``` +When the operating system executes a non-binary file, it reads the first line. +If the line begins with `#!`, the kernel uses it to determine which interpreter should execute the file. +The `#!` must be at the very start of the file, with no spaces or blank lines before it. -`echo` is a command that prints its arguments to standard output (which in our case is the terminal). -Bash splits the command into five words, and invokes the `echo` command with four arguments. -The extra spaces in the second example make no difference. -`echo` does not know how spaces were originally between the words. +Here, `env` searches `PATH` for the `bash` executable. +You may also see the simpler `#!/bin/bash`, which hard-codes the interpreter's location; the `env` form is more portable. -If we want to keep the extra whitespace, we need to pass the sentence as one single argument. -We can do this by using [quotes][Quotes]: +~~~~exercism/note +Do not be fooled by scripts or examples on the Internet that use `/bin/sh` as the interpreter. +**`sh` is not `bash`!** +Bash is "sh-compatible" and can run most `sh` scripts, but some Bash features will break or behave unexpectedly in `sh`. +~~~~ -```bash -$ echo "This is a test." -This is a test. -``` +## Comments -Quotes group everything inside them into a _single argument_. -The argument is `This is a test.` including those specific space characters. -Note that the quotes are not part of the argument — bash removes them before handing that single argument to `echo`. +A line beginning with `#` is a _comment_, and Bash ignores it. +A comment can also follow a command on the same line: everything from the `#` to the end of the line is ignored. +Comments exist for humans reading the script. -Arguments are separated from the command name and from each other by a whitespace. -This is important to remember. -For example, the following is wrong: +## Words and arguments -```bash -$ [-f file] -bash: [-f: command not found -``` +Bash reads commands from its input (which is usually either a terminal or a file). +Each line of input that it reads is treated as a _command_ — an instruction to be carried out. +(There are a few advanced cases, such as commands that span multiple lines, that will be discussed later.) -This is intended to test for the existence of a file named `file`. -It's reasonable to assume that whitespace around `[` and `]` doesn't matter, but `[` is actually a command, and it requires its last argument to be `]`. -(We will cover the `[` command in more detail later.) -Therefore, we must separate `[` from `-f` and `]` from `file`. -Otherwise bash will think we are trying to execute a command named `[-f` with a single argument `file]`. -The correct command separates all arguments with whitespace: +Bash divides each command into **words** that are demarcated by whitespace characters (spaces and tabs). +The first word is the name of the _command_ to be executed. +All the remaining words become _arguments_ to that command (options, filenames, etc.). -```bash -$ [ -f file ] -``` +A command can be a Bash _builtin_, such as `echo`, or an _executable_ program, such as `head`, `awk`, or `sed`. -(We see a lot of people who are confused by this behavior; they think that `[...]` is "just syntax" and they can omit the spaces; `[` is a command and the whitespace is required.) +## The `echo` command -If our filename contains whitespace or other special characters, it should also be quoted: +`echo` prints its arguments, separated by a single space, and finishes with a newline: ```bash -$ [ -f "my file" ] +echo flour sugar eggs ``` -## Types of commands - -Bash understands several different types of commands: aliases, functions, builtins, keywords, and executables. -These are all _commands_, and they all act in a very similar manner. - -By default aliases are only enabled in interactive shells, not shell scripts. -We won't cover them here. +outputs: -### Functions - -A function contains shell commands, and acts very much like a small script; they can even take arguments and create local variables. -When a function is called, the commands in it are executed. -Functions will be covered in depth later. - -### Builtins - -Bash has some basic commands built into it, such as: `cd` (change directory), `echo` (write output), and so on. -They can be thought of as functions that are already provided. - -### Keywords - -Keywords are like builtins, with the main difference being that keywords are actually bash syntax and may be parsed using special rules. -For example, `[` is a bash builtin, while `[[` is a bash keyword; they are both used to test for a variety of conditions. -But the `[[` keyword has some extra functionality. -For example, it provides the `=~` operator that does regular expression testing. - -```bash -$ [[ "hello world" =~ e.*o ]] # returns a "success" status -$ [ "hello world" =~ e.*o ] -bash: [: =~: binary operator expected +```text +flour sugar eggs ``` -The string comparison operators `<` and `>` are another example of how keywords parse the code differently. -Within `[[...]]`, these operators do not need any special care. +The amount of whitespace between arguments does not matter: ```bash -$ if [[ "$USER" < "n" ]]; then - echo "$USER is in the first half of the alphabet" -fi -# => glennj is in the first half of the alphabet +echo flour sugar eggs ``` -But within `[...]` you must quote or escape them to prevent the shell from parsing them as redirection operators. - -```bash -$ if [ "$USER" < "n" ]; then - echo "$USER is in the first half of the alphabet" -fi -# => bash: n: No such file or directory - -$ if [ "$USER" \< "n" ]; then - echo "$USER is in the first half of the alphabet" -fi -# => glennj is in the first half of the alphabet +```text +flour sugar eggs ``` +Calling `echo` without any arguments prints a blank line. -### Executables +## Options are just arguments -The last kind of command that can be executed by bash is an _executable_. -These are executable files (programs) on your computer's filesystem which you can run. -(Executables may also be called _external commands_ or _applications_.) -Executables are commonly invoked by typing only their name; the complete path to the file is typically not needed. -This can be done because bash uses a pre-defined variable which helps it find the location of common executable files. -This variable is called `PATH`. -It is a set of directory names separated by colons (e.g. `/usr/bin:/bin`). -When a command is specified (e.g. `myprogram`, or `ls`) without a file path (and it isn't an alias, function, builtin or keyword), bash searches through the directories in `PATH`. -The directories are searched in order, from left to right, to see whether they contain an executable with the given name. +Many commands accept _options_ that change how they behave. +To Bash, an option is nothing special: it is a word like any other, separated from its neighbors by whitespace. +The command itself decides how to interpret its arguments. +By convention, options begin with a `-`. -If the executable is outside a known path, the executable's file path will need to be specified. -For the `myprogram` executable in the current directory, use `./myprogram`; if it's in the directory `/opt/somedirectory`, use `/opt/somedirectory/myprogram`. - -Tip: The `type` command can be used to get detalis about the command: +The `head` command prints the first lines of a file. +Given a file `list.txt`: ```bash -$ type rm -rm is hashed (/bin/rm) -# or it might return: `rm is /bin/rm` - -$ type cd -cd is a shell builtin +head -n 2 list.txt ``` -## Scripts +Bash splits this line into four words: -A _script_ is a sequence of commands stored in a file. -Bash reads the file and processes the commands in order. -It moves on to the next command only when the current one has ended. -The exception being if a command has been specified to run asynchronously (in the background). -Don't worry too much about this case yet; we'll learn about how that works later on. +| Word | Role | +| ---------- | ------------------------------------------- | +| `head` | the command to execute | +| `-n` | an option, telling `head` to count _lines_ | +| `2` | the value for the `-n` option | +| `list.txt` | the file to read | -Any command line example in this guide can also be used in a script. +Bash passes the last three words to `head` unchanged. +It is `head` that understands that `-n` is followed by a number, and that the remaining word is a file. -Making a script is easy. -Begin by making a new file, and put this on the first line: +Because the whitespace is what separates the words, it matters where you put it. +`head -n 2` gives `head` two arguments (`-n` and `2`) while `head -n2` gives it one (`-n2`). +Many commands accept both forms, but that is up to the command. +Bash does not care; it only splits the line into words. + +## Quoting arguments + +[Quotes][Quotes] group words into a _single argument_. +Whitespace inside the quotes is preserved, and the quote characters themselves are not part of the argument: ```bash -#!/bin/bash +echo "flour sugar eggs" ``` -This line is called an _interpreter directive_ (it is also called a _hashbang_ or **_shebang_**). -It specifies that `/bin/bash` is to be used as the interpreter when the file is used as the executable in a command. -When the OS's kernel executes a _non-binary file_, it reads the first line of the file. -If the line begins with `#!`, the kernel uses the line to determine the interpreter to relay the file to. -(There are other valid ways to do this as well, see below.) -The `#!` must be at the very start of the file, with no spaces or blank lines before it. -Our script's commands will appear on separate lines below this. +```text +flour sugar eggs +``` -Tip: Instead of `#!/bin/bash` , you could use +If an argument such as a filename contains whitespace, quote it: ```bash -#!/usr/bin/env bash +head -n 1 my shopping list.txt # three files: "my", "shopping", "list.txt" +head -n 1 "my shopping list.txt" # one file ``` -`env` searches `$PATH` for the executable named by its first argument (in this case, "bash"). -For a more detailed explanation of this technique and how it differs from plain ol' `#!/bin/bash`, see [this question in StackOverflow][env bash]. - -Please do not be fooled by scripts or examples on the Internet that use `/bin/sh` as the interpreter. -**`sh` is not `bash`!** -Bash itself is a "sh-compatible" shell, meaning that it can run most `sh` scripts and carries much of the same syntax. -However, the opposite is not true; some features of bash will break or cause unexpected behavior in `sh`. -In fact, there is no single `sh` shell. -There are many shell implementations which support POSIX-sh syntax. -Depending on your OS, when you run `sh` you might actually be executing bash, ash, dash or some other shell. +## Running a script -Once the script file has been created, it can be executed by doing: +To run a script, pass it as an argument to the `bash` command: ```bash -$ bash myscript +bash myscript ``` -In this example, we execute the _command_ `bash` and tell it to read the script that we gave as an _argument_. -When we do it like this, the `#!` line is just a _comment_. +Used this way, the `#!` line is just a comment. +You are telling the operating system how to run the file. -Alternatively, we can give our scripts executable permissions. -With this method we can execute the script like any other executable instead of calling bash manually: +Alternatively, mark the script file as executable and run it like any other program: ```bash -$ chmod +x myscript # Mark the file as executable. -$ ./myscript # Now, myscript can be executed directly - # instead of having to specify bash. +chmod +x myscript +./myscript ``` -When we run the command this way, the operating system (OS) uses the `#!` line to determine which interpreter to use to run your script. - +Now the operating system uses the `#!` line to determine which interpreter to use. ## Credit The content of this lesson is taken from [Commands and Arguments] on the [Bash Guide]. - [Bash Guide]: https://mywiki.wooledge.org/BashGuide [Commands and Arguments]: https://mywiki.wooledge.org/BashGuide/CommandsAndArguments [Quotes]: https://mywiki.wooledge.org/Quotes -[glob]: https://mywiki.wooledge.org/glob -[posix]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap01.html -[env bash]: https://stackoverflow.com/questions/16365130/what-is-the-difference-between-usr-bin-env-bash-and-usr-bin-bash/16365367#16365367 diff --git a/config.json b/config.json index c8ce39fe..84af5f21 100644 --- a/config.json +++ b/config.json @@ -33,6 +33,18 @@ ] }, "exercises": { + "concept": [ + { + "slug": "shopping", + "name": "Shopping", + "uuid": "0e728e1f-386c-4cbe-9998-5179272fb6fa", + "concepts": [ + "commands-and-arguments" + ], + "prerequisites": [], + "status": "wip" + } + ], "practice": [ { "slug": "hello-world", diff --git a/exercises/concept/shopping/.docs/hints.md b/exercises/concept/shopping/.docs/hints.md new file mode 100644 index 00000000..44fc88f2 --- /dev/null +++ b/exercises/concept/shopping/.docs/hints.md @@ -0,0 +1,51 @@ +# Hints + +## General + +- A Bash script executes its commands in order. +- The [`echo` command][echo] can print literal output and blank lines. +- Use one `echo` command for each line of output that you print literally. + +## 1. Print the shopping list name + +- The first word of a command names the command to execute. +- The words after the command name are its arguments, including options and filenames. +- The starter code stores the script's first argument in the `shopping_list_file` variable. +- Any of these commands prints the first line of that file: + + ```bash + head -n 1 "$shopping_list_file" + awk 'NR == 1' "$shopping_list_file" + sed -n '1p' "$shopping_list_file" + ``` + +- The quotes keep the filename as one argument even if it contains spaces. +- Choose one command and use it as the first command in your script. + +## 2. Count the ingredients + +- Invoke `echo` without arguments to print the blank line before the count. +- The [`wc` command][wc] counts lines, words, or characters in a file. +- The `-l` option tells `wc` to count lines. +- This command counts the lines in `"$shopping_list_file"`: + + ```bash + wc -l "$shopping_list_file" + ``` + +- `wc` prints the count followed by the filename you gave it as an argument. +- Append the `echo` command and the `wc` command after your task 1 command. + +## 3. Print the buttermilk substitution + +- Invoke `echo` without arguments to print the blank line before the sentence. +- Quote the whole sentence to preserve its four consecutive spaces in a single argument: + + ```bash + echo "The substitution for buttermilk is regular milk" + ``` + +- Without quotes, Bash would split the sentence into separate arguments, and `echo` would print only one space between them. + +[echo]: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins +[wc]: https://www.gnu.org/software/coreutils/manual/html_node/wc-invocation.html diff --git a/exercises/concept/shopping/.docs/instructions.md b/exercises/concept/shopping/.docs/instructions.md new file mode 100644 index 00000000..8b29c46b --- /dev/null +++ b/exercises/concept/shopping/.docs/instructions.md @@ -0,0 +1,57 @@ +# Instructions + +You have a sudden craving for pancakes. +As a modern technically inclined person, you decide to write a Bash script that prints your shopping list. + +The complete shopping list is stored in a file. +Pass the filename to the script as its first command-line argument. +The starter code stores this argument in the `shopping_list_file` variable for you; variables will be covered later. +Each task adds to the same script, so preserve the output from the previous tasks. +Do not print anything other than the requested output. + +Run the script with: + +```bash +bash shopping.sh shopping-list.txt +``` + +## 1. Print the shopping list name + +Use `head`, `awk`, or `sed` (or any other tool you are familar with) to print only the first line of `"$shopping_list_file"`. +Read the name from the file instead of printing a hard-coded name with `echo`. +You do not need to learn these tools in depth for this exercise; the hints provide suitable commands. + +With the supplied file, the output should be: + +```text +Ingredients for pancakes +``` + +## 2. Count the ingredients + +Before you leave, you are curious just how many items are on this shopping list. +You do not need an exact ingredient count — the total number of lines in the file is a good enough approximation. + +Use `wc` to count the lines in `"$shopping_list_file"`. +Print a blank line after the shopping list name and before this count. + +With the supplied file, this task adds the following output after that blank line: + +```text +21 shopping-list.txt +``` + +## 3. Print the buttermilk substitution + +You arrive at the store and discover that it is out of buttermilk. +Fortunately, the substitutions section says that you can use regular milk. + +After the line count, print a blank line. +Then use `echo` to print the following sentence: + +```text +The substitution for buttermilk is regular milk +``` + +The four spaces between `is` and `regular milk` are intentional. +Your output must match it exactly. diff --git a/exercises/concept/shopping/.docs/introduction.md b/exercises/concept/shopping/.docs/introduction.md new file mode 100644 index 00000000..febaf9cd --- /dev/null +++ b/exercises/concept/shopping/.docs/introduction.md @@ -0,0 +1,153 @@ +# Introduction + +## Commands and Arguments + +This track is not about how to use bash as an interactive shell. +It is about learning to write programs using bash. + +A Bash program, or _script_, is a sequence of commands stored in a file. +Bash reads the file and executes the commands in order. + +### The shebang + +The first line of a script is usually an _interpreter directive_, also known as a _hashbang_ or _shebang_: + +```bash +#!/usr/bin/env bash +``` + +When the operating system executes a non-binary file, it reads the first line. +If the line begins with `#!`, the kernel uses it to determine which interpreter should execute the file. +The `#!` must be at the very start of the file, with no spaces or blank lines before it. + +Here, `env` searches `PATH` for the `bash` executable. +You may also see the simpler `#!/bin/bash`, which hard-codes the interpreter's location; the `env` form is more portable. + +~~~~exercism/note +Do not be fooled by scripts or examples on the Internet that use `/bin/sh` as the interpreter. +**`sh` is not `bash`!** +Bash is "sh-compatible" and can run most `sh` scripts, but some Bash features will break or behave unexpectedly in `sh`. +~~~~ + +### Comments + +A line beginning with `#` is a _comment_, and Bash ignores it. +A comment can also follow a command on the same line: everything from the `#` to the end of the line is ignored. +Comments exist for humans reading the script. + +### Words and arguments + +Bash reads commands from its input (which is usually either a terminal or a file). +Each line of input that it reads is treated as a _command_ — an instruction to be carried out. +(There are a few advanced cases, such as commands that span multiple lines, that will be discussed later.) + +Bash divides each command into **words** that are demarcated by whitespace characters (spaces and tabs). +The first word is the name of the _command_ to be executed. +All the remaining words become _arguments_ to that command (options, filenames, etc.). + +A command can be a Bash _builtin_, such as `echo`, or an _executable_ program, such as `head`, `awk`, or `sed`. + +### The `echo` command + +`echo` prints its arguments, separated by a single space, and finishes with a newline: + +```bash +echo flour sugar eggs +``` + +outputs: + +```text +flour sugar eggs +``` + +The amount of whitespace between arguments does not matter: + +```bash +echo flour sugar eggs +``` + +```text +flour sugar eggs +``` + +Calling `echo` without any arguments prints a blank line. + +### Options are just arguments + +Many commands accept _options_ that change how they behave. +To Bash, an option is nothing special: it is a word like any other, separated from its neighbors by whitespace. +The command itself decides how to interpret its arguments. +By convention, options begin with a `-`. + +The `head` command prints the first lines of a file. +Given a file `list.txt`: + +```bash +head -n 2 list.txt +``` + +Bash splits this line into four words: + +| Word | Role | +| ---------- | ------------------------------------------- | +| `head` | the command to execute | +| `-n` | an option, telling `head` to count _lines_ | +| `2` | the value for the `-n` option | +| `list.txt` | the file to read | + +Bash passes the last three words to `head` unchanged. +It is `head` that understands that `-n` is followed by a number, and that the remaining word is a file. + +Because the whitespace is what separates the words, it matters where you put it. +`head -n 2` gives `head` two arguments (`-n` and `2`) while `head -n2` gives it one (`-n2`). +Many commands accept both forms, but that is up to the command. +Bash does not care; it only splits the line into words. + +### Quoting arguments + +[Quotes][Quotes] group words into a _single argument_. +Whitespace inside the quotes is preserved, and the quote characters themselves are not part of the argument: + +```bash +echo "flour sugar eggs" +``` + +```text +flour sugar eggs +``` + +If an argument such as a filename contains whitespace, quote it: + +```bash +head -n 1 my shopping list.txt # three files: "my", "shopping", "list.txt" +head -n 1 "my shopping list.txt" # one file +``` + +### Running a script + +To run a script, pass it as an argument to the `bash` command: + +```bash +bash myscript +``` + +Used this way, the `#!` line is just a comment. +You are telling the operating system how to run the file. + +Alternatively, mark the script file as executable and run it like any other program: + +```bash +chmod +x myscript +./myscript +``` + +Now the operating system uses the `#!` line to determine which interpreter to use. + +### Credit + +The content of this lesson is taken from [Commands and Arguments] on the [Bash Guide]. + +[Bash Guide]: https://mywiki.wooledge.org/BashGuide +[Commands and Arguments]: https://mywiki.wooledge.org/BashGuide/CommandsAndArguments +[Quotes]: https://mywiki.wooledge.org/Quotes diff --git a/exercises/concept/shopping/.docs/introduction.md.tpl b/exercises/concept/shopping/.docs/introduction.md.tpl new file mode 100644 index 00000000..95da60db --- /dev/null +++ b/exercises/concept/shopping/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:commands-and-arguments} diff --git a/exercises/concept/shopping/.meta/config.json b/exercises/concept/shopping/.meta/config.json new file mode 100644 index 00000000..78ef1ba8 --- /dev/null +++ b/exercises/concept/shopping/.meta/config.json @@ -0,0 +1,23 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "shopping.sh" + ], + "test": [ + "shopping.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "editor": [ + "shopping-list.txt" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "blurb": "Learn how Bash scripts execute commands with arguments while printing a pancake shopping list." +} diff --git a/exercises/concept/shopping/.meta/design.md b/exercises/concept/shopping/.meta/design.md new file mode 100644 index 00000000..2b78161d --- /dev/null +++ b/exercises/concept/shopping/.meta/design.md @@ -0,0 +1,36 @@ +# Design + +## Goal + +The goal of this exercise is to introduce commands and arguments in Bash scripts. + +## Learning objectives + +- Understand that a script is a sequence of commands executed in order. +- Distinguish a command name from its arguments. +- Understand that whitespace separates command words. +- Pass options, command programs, and filenames as arguments to executable commands. +- Use `echo` with zero, one, or several arguments to produce output. +- Use basic quoting to group words and preserve whitespace in an argument. +- Recognize the shebang and comments in a script. + +## Out of scope + +- Declaring variables and handling positional parameters; the filename variable is provided. +- Reading standard input. +- Detailed usage of `head`, `wc`, or other text-processing tools. +- Conditionals and loops. +- Functions. +- Arrays and arithmetic. +- Pipelines and redirection. +- Quoting beyond simple literal arguments. + +## Concepts + +The Concepts this exercise unlocks are: + +- `commands-and-arguments` + +## Prerequisites + +None. diff --git a/exercises/concept/shopping/.meta/exemplar.sh b/exercises/concept/shopping/.meta/exemplar.sh new file mode 100644 index 00000000..da97f33c --- /dev/null +++ b/exercises/concept/shopping/.meta/exemplar.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +shopping_list_file=$1 + +# Task 1 +head -n 1 "$shopping_list_file" + +# Task 2 +echo +wc -l "$shopping_list_file" + +# Task 3 +echo +echo "The substitution for buttermilk is regular milk" diff --git a/exercises/concept/shopping/bats-extra.bash b/exercises/concept/shopping/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/shopping/bats-extra.bash @@ -0,0 +1,642 @@ +# This is the source code for bats-support and bats-assert, concatenated +# * https://github.com/bats-core/bats-support +# * https://github.com/bats-core/bats-assert +# +# Comments have been removed to save space. See the git repos for full source code. + +############################################################ +# +# bats-support - Supporting library for Bats test helpers +# +# Written in 2016 by Zoltan Tombol +# +# To the extent possible under law, the author(s) have dedicated all +# copyright and related and neighboring rights to this software to the +# public domain worldwide. This software is distributed without any +# warranty. +# +# You should have received a copy of the CC0 Public Domain Dedication +# along with this software. If not, see +# . +# + +# shellcheck disable=SC2120 # (warning): fail references arguments, but none are ever passed. +fail() { + # shellcheck disable=2015 # (info): Note that A && B || C is not if-then-else. C may run when A is true. + (( $# == 0 )) && batslib_err || batslib_err "$@" + return 1 +} + +batslib_is_caller() { + local -i is_mode_direct=1 + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -i|--indirect) is_mode_direct=0; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + # Arguments. + local -r func="$1" + + # Check call stack. + if (( is_mode_direct )); then + [[ $func == "${FUNCNAME[2]}" ]] && return 0 + else + local -i depth + for (( depth=2; depth<${#FUNCNAME[@]}; ++depth )); do + [[ $func == "${FUNCNAME[$depth]}" ]] && return 0 + done + fi + + return 1 +} + +batslib_err() { + { if (( $# > 0 )); then + echo "$@" + else + cat - + fi + } >&2 +} + +batslib_count_lines() { + local -i n_lines=0 + local line + while IFS='' read -r line || [[ -n $line ]]; do + (( ++n_lines )) + done < <(printf '%s' "$1") + echo "$n_lines" +} + +batslib_is_single_line() { + for string in "$@"; do + (( $(batslib_count_lines "$string") > 1 )) && return 1 + done + return 0 +} + +batslib_get_max_single_line_key_width() { + local -i max_len=-1 + while (( $# != 0 )); do + local -i key_len="${#1}" + batslib_is_single_line "$2" && (( key_len > max_len )) && max_len="$key_len" + shift 2 + done + echo "$max_len" +} + +batslib_print_kv_single() { + local -ir col_width="$1"; shift + while (( $# != 0 )); do + printf '%-*s : %s\n' "$col_width" "$1" "$2" + shift 2 + done +} + +batslib_print_kv_multi() { + while (( $# != 0 )); do + printf '%s (%d lines):\n' "$1" "$( batslib_count_lines "$2" )" + printf '%s\n' "$2" + shift 2 + done +} + +batslib_print_kv_single_or_multi() { + local -ir width="$1"; shift + local -a pairs=( "$@" ) + + local -a values=() + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + values+=( "${pairs[$i]}" ) + done + + if batslib_is_single_line "${values[@]}"; then + batslib_print_kv_single "$width" "${pairs[@]}" + else + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + pairs[i]="$( batslib_prefix < <(printf '%s' "${pairs[$i]}") )" + done + batslib_print_kv_multi "${pairs[@]}" + fi +} + +batslib_prefix() { + local -r prefix="${1:- }" + local line + while IFS='' read -r line || [[ -n $line ]]; do + printf '%s%s\n' "$prefix" "$line" + done +} + +batslib_mark() { + local -r symbol="$1"; shift + # Sort line numbers. + # shellcheck disable=SC2046 # (warning): Quote this to prevent word splitting. + set -- $( sort -nu <<< "$( printf '%d\n' "$@" )" ) + + local line + local -i idx=0 + while IFS='' read -r line || [[ -n $line ]]; do + if (( ${1:--1} == idx )); then + printf '%s\n' "${symbol}${line:${#symbol}}" + shift + else + printf '%s\n' "$line" + fi + (( ++idx )) + done +} + +batslib_decorate() { + echo + echo "-- $1 --" + cat - + echo '--' + echo +} + +############################################################ + +assert() { + if ! "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion failed' \ + | fail + fi +} + +assert_equal() { + if [[ $1 != "$2" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$2" \ + 'actual' "$1" \ + | batslib_decorate 'values do not equal' \ + | fail + fi +} + +assert_failure() { + : "${output?}" + : "${status?}" + + (( $# > 0 )) && local -r expected="$1" + if (( status == 0 )); then + batslib_print_kv_single_or_multi 6 'output' "$output" \ + | batslib_decorate 'command succeeded, but it was expected to fail' \ + | fail + elif (( $# > 0 )) && (( status != expected )); then + { local -ir width=8 + batslib_print_kv_single "$width" \ + 'expected' "$expected" \ + 'actual' "$status" + batslib_print_kv_single_or_multi "$width" \ + 'output' "$output" + } \ + | batslib_decorate 'command failed as expected, but status differs' \ + | fail + fi +} + +assert_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Arguments. + local -r expected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $expected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if ! [[ ${lines[$idx]} =~ $expected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression does not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} != *"$expected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line does not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} != "$expected" ]]; then + batslib_print_kv_single 8 \ + 'index' "$idx" \ + 'expected' "$expected" \ + 'actual' "${lines[$idx]}" \ + | batslib_decorate 'line differs' \ + | fail + fi + fi + else + # Contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} =~ $expected ]] && return 0 + done + { local -ar single=( 'regexp' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line matches regular expression' \ + | fail + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == *"$expected"* ]] && return 0 + done + { local -ar single=( 'substring' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line contains substring' \ + | fail + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == "$expected" ]] && return 0 + done + { local -ar single=( 'line' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'output does not contain line' \ + | fail + fi + fi +} + +assert_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_nonempty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_nonempty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + return $? + fi + + # Arguments. + local expected + if (( use_stdin )); then + expected="$(cat -)" + else + expected="${1-}" + fi + + # Matching. + if (( is_mode_nonempty )); then + if [ -z "$output" ]; then + echo 'expected non-empty output, but output was empty' \ + | batslib_decorate 'no output' \ + | fail + fi + elif (( is_mode_regexp )); then + # shellcheck disable=SC2319 # (warning) `$?` in a conditional expression: https://github.com/koalaman/shellcheck/wiki/SC2319 + if [[ '' =~ $expected ]] || (( $? == 2 )); then + # the regex matches an empty string or it is syntactically incorrect. + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + elif ! [[ $output =~ $expected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression does not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output != *"$expected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'output does not contain substring' \ + | fail + fi + else + if [[ $output != "$expected" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$expected" \ + 'actual' "$output" \ + | batslib_decorate 'output differs' \ + | fail + fi + fi +} + +assert_success() { + : "${output?}" + : "${status?}" + + if (( status != 0 )); then + { local -ir width=6 + batslib_print_kv_single "$width" 'status' "$status" + batslib_print_kv_single_or_multi "$width" 'output' "$output" + } \ + | batslib_decorate 'command failed' \ + | fail + fi +} + +refute() { + if "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion succeeded, but it was expected to fail' \ + | fail + fi +} + +refute_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Arguments. + local -r unexpected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if [[ ${lines[$idx]} =~ $unexpected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression should not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} == "$unexpected" ]]; then + batslib_print_kv_single 5 \ + 'index' "$idx" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should differ' \ + | fail + fi + fi + else + # Line contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} =~ $unexpected ]]; then + { local -ar single=( 'regexp' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should match the regular expression' \ + | fail + return $? + fi + done + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + { local -ar single=( 'substring' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should contain substring' \ + | fail + return $? + fi + done + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == "$unexpected" ]]; then + { local -ar single=( 'line' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'line should not be in output' \ + | fail + return $? + fi + done + fi + fi +} + +refute_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_empty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_empty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Arguments. + local unexpected + if (( use_stdin )); then + unexpected="$(cat -)" + else + unexpected="${1-}" + fi + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Matching. + if (( is_mode_empty )); then + if [ -n "$output" ]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output non-empty, but expected no output' \ + | fail + fi + elif (( is_mode_regexp )); then + if [[ $output =~ $unexpected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression should not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output == *"$unexpected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'output should not contain substring' \ + | fail + fi + else + if [[ $output == "$unexpected" ]]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output equals, but it was expected to differ' \ + | fail + fi + fi +} diff --git a/exercises/concept/shopping/shopping-list.txt b/exercises/concept/shopping/shopping-list.txt new file mode 100644 index 00000000..da1ef245 --- /dev/null +++ b/exercises/concept/shopping/shopping-list.txt @@ -0,0 +1,21 @@ +Ingredients for pancakes + +Required ingredients +1 cup flour +0.25 cup sugar +1 teaspoon baking powder +0.25 teaspoon baking soda +1 pinch salt +1 cup buttermilk +1 egg +1 tablespoon melted butter + +Optional ingredients +0.25 teaspoon cinnamon +0.5 teaspoon vanilla extract +0.25 cup blueberries + +Substitutions +buttermilk: regular milk +melted butter: vegetable oil +blueberries: chopped apple diff --git a/exercises/concept/shopping/shopping.bats b/exercises/concept/shopping/shopping.bats new file mode 100644 index 00000000..31769fb6 --- /dev/null +++ b/exercises/concept/shopping/shopping.bats @@ -0,0 +1,50 @@ +#!/usr/bin/env bats +load bats-extra + +# `run --keep-empty-lines` keeps the blank lines between tasks in $lines, +# so that assert_line --index numbers match the visible output. +bats_require_minimum_version 1.5.0 + +# bats test_tags=task:1 +test_print_shopping_list_name() { # @test + run --keep-empty-lines bash shopping.sh shopping-list.txt + + assert_success + assert_line --index 0 "Ingredients for pancakes" +} + +# bats test_tags=task:1 +test_read_shopping_list_name_from_file() { # @test + list_file="${BATS_TEST_TMPDIR}/different-shopping-list.txt" + printf 'A different shopping list\n' > "$list_file" + + run --keep-empty-lines bash shopping.sh "$list_file" + + assert_success + assert_line --index 0 "A different shopping list" +} + +# bats test_tags=task:2 +test_count_shopping_list_lines() { # @test + run --keep-empty-lines bash shopping.sh shopping-list.txt + + assert_success + assert_line --index 1 "" + # `wc` output formatting (padding of the count) varies between + # implementations (e.g. GNU vs BSD/macOS), so match loosely. + assert_line --index 2 --regexp '^[[:space:]]*21[[:space:]]+shopping-list\.txt$' +} + +# bats test_tags=task:3 +test_print_buttermilk_substitution() { # @test + run bash shopping.sh shopping-list.txt + + assert_success + # `wc` output formatting (padding of the count) varies between + # implementations (e.g. GNU vs BSD/macOS), so match loosely. + assert_output --regexp '^Ingredients for pancakes + +[[:space:]]*21[[:space:]]+shopping-list\.txt + +The substitution for buttermilk is regular milk$' +} diff --git a/exercises/concept/shopping/shopping.sh b/exercises/concept/shopping/shopping.sh new file mode 100644 index 00000000..6b8db3df --- /dev/null +++ b/exercises/concept/shopping/shopping.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 + +# The first command-line argument is the shopping list filename. +# This assignment stores it in a variable for you to use in your commands. +# You do not need to learn about variables yet. + +shopping_list_file=$1 + +# Add commands below each task comment to print the shopping list. +# Each task builds on the previous tasks, so keep the earlier output unchanged. + +# Task 1: print the first line of "$shopping_list_file". + +# Task 2: print a blank line, then count the lines in "$shopping_list_file". + +# Task 3: print a blank line, then use echo to print the buttermilk substitution. +# Preserve the four spaces before "regular milk" shown in the instructions.