diff --git a/POLICIES.md b/POLICIES.md index cd0cf3f2..18c66747 100644 --- a/POLICIES.md +++ b/POLICIES.md @@ -26,7 +26,13 @@ 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 -### Prefer standard Bash over POSIX compliance +### 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. This applies when discussing sumbissions for the exercises. 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..8c110b82 100644 --- a/concepts/commands-and-arguments/introduction.md +++ b/concepts/commands-and-arguments/introduction.md @@ -1,282 +1,151 @@ -# Introduction to Shell Fundamentals +# Introduction to Commands and Arguments -## 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. +This track is not about how to use bash as an interactive shell. +It is about learning to write programs using bash, the programming language. -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. +A bash program, or _script_, is a sequence of commands stored in a file. +bash (the executable) reads the file and executes the commands in order. -**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: +## The shebang -* 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. +The first line of a script is usually an _interpreter directive_, also known as a _hashbang_ or _shebang_: -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 +#!/usr/bin/env bash +``` -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.) +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. -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.). +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 -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. +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 -# 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 -``` +## Comments -`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. +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. -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: +## Words and arguments -```bash -$ echo This is a test. -This is a test. -$ echo This is a test. -This is a test. -``` - -`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. +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.) -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]: +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 -$ echo "This is a test." -This is a test. -``` +A command can be a bash _builtin_, such as `echo`, or an _executable_ program, such as `head`, `awk`, or `sed`. -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`. +## The `echo` command -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: +`echo` prints its arguments, separated by a single space, and finishes with a newline: ```bash -$ [-f file] -bash: [-f: command not found +echo flour sugar eggs ``` -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: +outputs: -```bash -$ [ -f file ] +```text +flour sugar eggs ``` -(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.) - -If our filename contains whitespace or other special characters, it should also be quoted: +The amount of whitespace between arguments does not matter: ```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. - -### 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. +```text +flour sugar eggs +``` -### Keywords +Calling `echo` without any arguments prints a blank line. -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. +## Options are just arguments -```bash -$ [[ "hello world" =~ e.*o ]] # returns a "success" status -$ [ "hello world" =~ e.*o ] -bash: [: =~: binary operator expected -``` +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 string comparison operators `<` and `>` are another example of how keywords parse the code differently. -Within `[[...]]`, these operators do not need any special care. +The `head` command prints the first lines of a file. +Given a file `list.txt`: ```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 +head -n 2 list.txt ``` -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 -``` +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 | -### Executables +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. -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. +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. -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`. +## Quoting arguments -Tip: The `type` command can be used to get detalis about the command: +[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 -$ type rm -rm is hashed (/bin/rm) -# or it might return: `rm is /bin/rm` - -$ type cd -cd is a shell builtin +echo "flour sugar eggs" ``` -## Scripts - -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. - -Any command line example in this guide can also be used in a script. - -Making a script is easy. -Begin by making a new file, and put this on the first line: - -```bash -#!/bin/bash +```text +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. - -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..e5968df3 --- /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..c9e03794 --- /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..f32652c8 --- /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, the programming language. + +A bash program, or _script_, is a sequence of commands stored in a file. +bash (the executable) 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..95ec5243 --- /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..a8857e74 --- /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.