diff --git a/concepts/README.md b/concepts/README.md index 5c92c4bd..587f7445 100644 --- a/concepts/README.md +++ b/concepts/README.md @@ -129,6 +129,11 @@ Redirection ||--|| "Here Documents" : "" - option parsing with getopts +- advanced topics expanding on previous topics (see the "advanced-*.md" files): + - word splitting + - filename expansion + - globbing + - `set` command and "strict mode" - pros and cons of diff --git a/concepts/advanced-filename-expansion.md b/concepts/advanced-filename-expansion.md new file mode 100644 index 00000000..a5b86336 --- /dev/null +++ b/concepts/advanced-filename-expansion.md @@ -0,0 +1,27 @@ +# Advanced Filename Expansion + +(Note this material is for a future concept) + +## Disable Filename Expansion + +You can use the [`set`][set] command to disable filename expansion. + +```bash +echo * # prints a list of files +set -f # disable filename expansion +echo * # prints a literal asterisk +set +f # enable filename expansion +``` + +## Controlling Filename Expansion + +There are several settings for the builtin [`shopt`][shopt] command that control how filename expansion operates. +A couple of interesting ones are: + +* `shopt -s nocaseglob` -- perform case insensitive matching +* `shopt -s extglob` -- enable extended patterns +* `shopt -s nullglob` -- if no files match, replace the pattern with nothing. + The default behaviour is to leave the pattern in place as a literal string. + +[set]: https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin +[shopt]: https://www.gnu.org/software/bash/manual/bash.html#The-Shopt-Builtin diff --git a/concepts/advanced-globbing.md b/concepts/advanced-globbing.md new file mode 100644 index 00000000..f7c83f08 --- /dev/null +++ b/concepts/advanced-globbing.md @@ -0,0 +1,67 @@ +# Advanced Globbing + +(Note this material is for a future concept) + +## Character Sets + +There are lots of details about character sets in glob patterns. + +* `[abc]` matches exactly one character that is either an `a` or a `b` or a `c`. + * to include a literal close bracket in the expression, make it the first character after the opening bracket (after an optional `^`) + * `[][]` is a character set that will match either a close or an open bracket. + * or escape it with a backslash: `[[\]]` +* `[x-y]` matches exactly one character that is in the _range_ from `x` to `y` + * to include a literal hyphen character in a character set, it must be either the first character after the opening bracket (after an optional `^`) or the last character before the closing bracket. + * `[-xy]` or `[xy-]` each match exactly one character that is an `-` or a `x` or a `y` + * or escape it with a backslash: `[x\-y]` + * multiple ranges can be specified, for example `[0-9A-Fa-f]` matches a hexadecimal digit +* `[^abc]` matches exactly one character that is **NOT** an `a` or a `b` or a `c`, +* `[^x-y]` matches exactly one character that is **NOT** in the range from `x` to `y` +* `[[:character_class:]]` matches one character that is in the named "character_class" + * the available character classes are: + * `lower` -- lowercase letters + * `upper` -- uppercase letters + * `alpha` -- letters + * `digit` -- digits + * `alnum` -- letters and digits + * `space` -- whitespace + * `blank` -- horizontal whitespace (space and tab) + * `xdigit` -- hexadecimal digits + * `word` -- characters allowed in an identifier (letters, numbers, underscore) + * `punct` -- punctuation + * `cntrl` -- control characters + * `graph` -- "visible" characters + * `print` -- visible characters plus space + * they can be combined: + * the `[[:alpha:]]` class consists of `[[:lower:][:upper:]]` + * the `[[:alnum:]]` class consists of `[[:alpha:][:digit:]]` + * the `[[:word:]]` class consists of `[[:alnum:]_]` + * underscore (octal 137) is both `[[:word:]]` and `[[:punct:]]` + * the `[[:graph:]]` class consists of `[[:alnum:][:punct:]]` + * the `[[:print:]]` class consists of `[[:graph:] ]` -- just space (octal 040) not any other whitespace. + +## Glob Patterns Are Not Regular Expressions + +Glob patterns **are not** regular expressions. + +A glob pattern must match the _entire_ filename, but a regular expression can match only part of a string. +For example, the glob `a` matches only a file named exactly `a`, while the regex `a` matches any string that contains an `a`. +To get the same result with a glob, use `*a*`. + +* match exactly one character + * regex `.` + * glob `?` +* match zero or more characters + * regex `.*` + * glob `*` + * the glob pattern `.*` means "match a filename where the first character is a literal dot followed by zero or more of any characters". +* match one or more characters + * regex `.+` + * glob `?*` +* regex character sets and glob character sets act the same way. + +## Extended Patterns + +Bash provides [extended patterns][extended-patterns] that are closer to regular expressions. + +[extended-patterns]: https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching diff --git a/concepts/advanced-word-splitting.md b/concepts/advanced-word-splitting.md new file mode 100644 index 00000000..993faefd --- /dev/null +++ b/concepts/advanced-word-splitting.md @@ -0,0 +1,38 @@ +# Advanced Word Splitting + +(Note this material is for a future concept) + +Any results of parameter expansion, command substitution or arithmetic expansion _that did not occur within double quotes_ are eligible for "word splitting". +The shell takes the expanded result, and splits it on any sequence of characters present in the value of `$IFS`. +By default, this is space, tab and newline. + +Let's see it with a different value of `$IFS`: + +```bash +csv="first,second,third" +IFS="," +for word in $csv; do echo "$word"; done +``` +outputs +```none +first +second +third +``` + +## Disable Word Splitting + +A technique to disable word splitting is to set `$IFS` to an empty string + +```bash +sentence="The quick brown fox jumps." +IFS= # or explicitly, IFS="" +printf '%s\n' $sentence +``` +outputs +```none +The quick brown fox jumps. +``` + +However, leaving variables unquoted is not recommended unless you also disable Filename Expansion. +See [Advanced Filename Expansion](advanced-filename-expansion.md) to learn how. diff --git a/concepts/quoting/about.md b/concepts/quoting/about.md index 28875ee6..3828cc65 100644 --- a/concepts/quoting/about.md +++ b/concepts/quoting/about.md @@ -12,7 +12,7 @@ You don't want the value to be unexpectedly handled as two or more separate stri ## Quoting Quoting is the primary mechanism to ensure that a piece of text is treated as a single word. -There are two main type of quotes. +There are two main types of quotes. ### Double Quotes @@ -50,71 +50,45 @@ Two of the last expansions are _Word Splitting_ and _Filename Expansion_. ### Word Splitting Any results of parameter expansion, command substitution or arithmetic expansion _that did not occur within double quotes_ are eligible for "word splitting". -The shell takes the expanded result, and splits it on any sequence of characters present in the value of `$IFS`. -By default, this is space, tab and newline. +The shell splits the expanded result into separate words on spaces, tabs and newlines. -We can see this in action using a shell loop: +The `printf '%s\n'` command prints each of its arguments on a line of its own, so it shows how many words a command receives: ```bash sentence="The quick brown fox jumps." -i=0 -for word in "$sentence"; do echo "$((++i)) $word"; done -# ..........^.........^ +printf '%s\n' "$sentence" ``` outputs ```none -1 The quick brown fox jumps. +The quick brown fox jumps. ``` But unquoted: ```bash -i=0 -for word in $sentence; do echo "$((++i)) $word"; done -# .........^.........^ +printf '%s\n' $sentence ``` outputs ```none -1 The -2 quick -3 brown -4 fox -5 jumps. +The +quick +brown +fox +jumps. ``` -Let's see it with a different value of `$IFS`: +#### Preserving Whitespace -```bash -csv="first,second,third" -IFS="," -for word in $csv; do echo "$word"; done -``` -outputs -```none -first -second -third -``` - -#### Disable Word Splitting - -A techique to disable word splitting is to set `$IFS` to an empty string +Recall from the introduction to Commands and Arguments that quotes preserve repeated whitespace. +This also applies to variables. +Unquoted, the value is split into words, and `echo` joins those words with single spaces. ```bash -sentence="The quick brown fox jumps." -IFS= # or explicitly, IFS="" -i=0 -for word in $sentence; do echo "$((++i)) $word"; done -# .........^.........^ -``` -outputs -```none -1 The quick brown fox jumps. +message="two spaces" +echo $message # prints: two spaces +echo "$message" # prints: two spaces ``` -However, leaving variables unquoted is not recommended unless you also disable Filename Expansion. -We'll see how to do that below. - ### Filename Expansion "Glob" patterns are used to express a concise pattern to match a set of files. @@ -127,47 +101,34 @@ The glob wildcard characters are: * `?` matches exactly one of any character, * `[...]` matches exactly one character from the set of characters listed inside the brackets. - ~~~~exercism/advanced -
- There are lots of details about character sets. - Click here to show them. - - - * `[abc]` matches exactly one character that is either an `a` or a `b` or a `c`. - * to include a literal close bracket in the expression, make it the first character after the opening bracket (after an optional `^`) - * `[][]` is a character set that will match either a close or an open bracket. - * or escape it with a backslash: `[[\]]` - * `[x-y]` matches exactly one character that is in the _range_ from `x` to `y` - * to include a literal hyphen character in a character set, it must be either the first character after the opening bracket (after an optional `^`) or the last character before the closing bracket. - * `[-xy]` or `[xy-]` each match exactly one character that is an `-` or a `x` or a `y` - * or escape it with a backslash: `[x\-y]` - * multiple ranges can be specified, for example `[0-9A-Fa-f]` matches a hexadecimal digit - * `[^abc]` matches exactly one character that is **NOT** an `a` or a `b` or a `c`, - * `[^x-y]` matches exactly one character that is **NOT** in the range from `x` to `y` - * `[[:character_class:]]` matches one character that is in the named "character_class" - * the available character classes are: - * `lower` -- lowercase letters - * `upper` -- uppercase letters - * `alpha` -- letters - * `digit` -- digits - * `alnum` -- letters and digits - * `space` -- whitespace - * `blank` -- horizontal whitespace (space and tab) - * `xdigit` -- hexadecimal digits - * `word` -- characters allowed in an identifier (letters, numbers, underscore) - * `punct` -- punctuation - * `cntrl` -- control characters - * `graph` -- "visible" characters - * `print` -- visible characters plus space - * they can be combined: - * the `[[:alpha:]]` class consists of `[[:lower:][:upper:]]` - * the `[[:alnum:]]` class consists of `[[:alpha:][:digit:]]` - * the `[[:word:]]` class consists of `[[:alnum:]_]` - * underscore (octal 137) is both `[[:word:]]` and `[[:punct:]]` - * the `[[:graph:]]` class consists of `[[:alnum:][:punct:]]` - * the `[[:print:]]` class consists of `[[:graph:] ]` -- just space (octal 040) not any other whitespace. -
- ~~~~ +Glob patterns **are not** regular expressions. +For example, a glob must match the _entire_ filename, but a regular expression can match only part of a string. + +#### Filename Expansion Is Done by the Shell + +You have probably used globs with `ls`: + +```bash +ls *.md +``` + +Filename expansion is a feature of the _shell_, not of the `ls` program. +If the directory contains `a.md` and `b.md`, then `ls` is run as `ls a.md b.md`: `ls` never sees the `*`. +Every command gets the same treatment, which is why `echo *.md` prints the file names too. + +#### Quoting Part of a Pattern + +Quotes can cover just part of a word. +This lets you write a pattern in your script while keeping a variable's value literal: + +```bash +extension='md' +echo "*.$extension" # prints *.md +echo *."$extension" # prints a list of Markdown files +``` + +In the last line, the unquoted `*` is expanded by the shell. +The characters in `$extension` are quoted, so they are never split into words or treated as wildcards, whatever the value contains. #### Iterating Over a List of Files @@ -183,45 +144,40 @@ Note that the variable `"$file"` is quoted. The glob pattern can return files that contain spaces in the name. We need to quote the variable so that the `do_something_with` command receives exactly one argument, the file name. -#### Glob Patterns Are Not Regular Expressions - -Glob patterns **are not** regular expressions. - -* match exactly one character - * regex `.` - * glob `?` -* match zero or more characters - * regex `.*` - * glob `*` - * the glob pattern `.*` means "match a filename where the first character is a literal dot followed by zero or more of any characters". -* match one or more characters - * regex `.+` - * glob `?*` -* regex character sets and glob character sets act the same way. - -~~~~exercism/advanced -Bash provides [extended patterns][extended-patterns] that are closer to regular expressions. - -[extended-patterns]: https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching -~~~~ - #### Quoting and Filename Expansion There are times when you want to suppress filename expansion. Handling user input is one such time. -Consider this code snippet +This script is meant to repeat the user's answer back to them: ```bash -read -p "Enter something: " user_input -echo $user_input +read -p "What is your favourite punctuation mark? " mark +echo You chose: $mark +``` + +If the user enters an asterisk (`*`), the script should print `You chose: *`. +Instead, because `$mark` is not quoted, the shell replaces the asterisk with the names of the files in the current directory. +If that directory contains `a.md` and `b.md`, the output is + +```none +You chose: a.md b.md ``` -If the user enters an asterisk (`*`), what will be output? -The list of files in the current directory. -That's probably not what you want to do. +Quote the string to print exactly what the user entered: + +```bash +echo "You chose: $mark" +``` + +outputs + +```none +You chose: * +``` -Another example is to pass patterns as arguments to programs that expect patterns. -The `tr` program is often used for text manipulation. To lowercase a variable value, you can do this +Another example is when a program takes literal patterns as arguments. +The `tr` program is often used for text manipulation. +To lowercase a variable value, you can do this: ```bash var="My Puppet" @@ -235,9 +191,12 @@ my puppet A common mistake is to forget to quote `tr`'s arguments: `tr [:upper:] [:lower:]` ~~~~exercism/caution -Why is that a problem? -Unquoted glob patterns will be expanded to the list of files that match. -Suppose the person using your script has a files named `p` and `u` and `w` in the current directory: +Why is that a problem? +To the shell, an unquoted `[:upper:]` is a glob pattern that matches a file whose name is one of the characters `:`, `u`, `p`, `e` or `r`. +Likewise, `[:lower:]` matches a file named `:`, `l`, `o`, `w`, `e` or `r`. + +If no files match, bash leaves the patterns unchanged by default, and the command works. +But suppose the person using your script has files named `p`, `u` and `w` in the current directory: ```bash touch p u w @@ -245,42 +204,14 @@ var="My Puppet" echo "$var" | tr [:upper:] [:lower:] ``` -This results in an error! - -The unquoted `[:upper:]` pattern matches any of `:`, `u`, `p`, `e` or `r`. -The unquoted `[:lower:]` pattern matches any of `:`, `l`, `o`, `w`, `e` or `r`. -Bash matches the files `p` and `u` for the first pattern, and the file `w` for the second pattern, and `tr` is invoked like +Bash replaces the first pattern with `p u` and the second with `w`, so it runs this instead: ```bash echo "$var" | tr p u w ``` -And that's the wrong number of arguments for `tr`. +`tr` fails with an error because it received three arguments instead of two. ~~~~ -#### Disable Filename Expansion - -You can use the [`set`][set] command to disable filename expansion. - -```bash -echo * # prints a list of files -set -f # disable filename expansion -echo * # prints a literal asterisk -set +f # enable filename expansion -``` - -#### Controlling Filename Expansion - -There are several settings for the builtin [`shopt`][shopt] command that control how filename expansion operates. -A couple of interesting ones are: - -* `shopt -s nocaseglob` -- perform case insensitive matching -* `shopt -s extglob` -- enable extended patterns -* `shopt -s nullglob` -- if no files match, replace the pattern with nothing. - The default behaviour is to leave the pattern in place as a literal string. - - [expansions]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions [glob]: https://en.wikipedia.org/wiki/Glob_(programming) -[set]: https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin -[shopt]: https://www.gnu.org/software/bash/manual/bash.html#The-Shopt-Builtin diff --git a/concepts/quoting/introduction.md b/concepts/quoting/introduction.md index 25c3b599..af61e449 100644 --- a/concepts/quoting/introduction.md +++ b/concepts/quoting/introduction.md @@ -12,7 +12,7 @@ You don't want the value to be unexpectedly handled as two or more separate stri ## Quoting Quoting is the primary mechanism to ensure that a piece of text is treated as a single word. -There are two main type of quotes. +There are two main types of quotes. ### Double Quotes @@ -50,71 +50,45 @@ Two of the last expansions are _Word Splitting_ and _Filename Expansion_. ### Word Splitting Any results of parameter expansion, command substitution or arithmetic expansion _that did not occur within double quotes_ are eligible for "word splitting". -The shell takes the expanded result, and splits it on any sequence of characters present in the value of `$IFS`. -By default, this is space, tab and newline. +The shell splits the expanded result into separate words on spaces, tabs and newlines. -We can see this in action using a shell loop: +The `printf '%s\n'` command prints each of its arguments on a line of its own, so it shows how many words a command receives: ```bash sentence="The quick brown fox jumps." -i=0 -for word in "$sentence"; do echo "$((++i)) $word"; done -# ..........^.........^ +printf '%s\n' "$sentence" ``` outputs ```none -1 The quick brown fox jumps. +The quick brown fox jumps. ``` But unquoted: ```bash -i=0 -for word in $sentence; do echo "$((++i)) $word"; done -# .........^.........^ +printf '%s\n' $sentence ``` outputs ```none -1 The -2 quick -3 brown -4 fox -5 jumps. +The +quick +brown +fox +jumps. ``` -Let's see it with a different value of `$IFS`: +#### Preserving Whitespace -```bash -csv="first,second,third" -IFS="," -for word in $csv; do echo "$word"; done -``` -outputs -```none -first -second -third -``` - -#### Disable Word Splitting - -A techique to disable word splitting is to set `$IFS` to an empty string +Recall from the introduction to Commands and Arguments that quotes preserve repeated whitespace. +This also applies to variables. +Unquoted, the value is split into words, and `echo` joins those words with single spaces. ```bash -sentence="The quick brown fox jumps." -IFS= # or explicitly, IFS="" -i=0 -for word in $sentence; do echo "$((++i)) $word"; done -# .........^.........^ -``` -outputs -```none -1 The quick brown fox jumps. +message="two spaces" +echo $message # prints: two spaces +echo "$message" # prints: two spaces ``` -However, leaving variables unquoted is not recommended unless you also disable Filename Expansion. -We'll see how to do that below. - ### Filename Expansion "Glob" patterns are used to express a concise pattern to match a set of files. @@ -127,47 +101,35 @@ The glob wildcard characters are: * `?` matches exactly one of any character, * `[...]` matches exactly one character from the set of characters listed inside the brackets. - ~~~~exercism/advanced -
- There are lots of details about character sets. - Click here to show them. - - - * `[abc]` matches exactly one character that is either an `a` or a `b` or a `c`. - * to include a literal close bracket in the expression, make it the first character after the opening bracket (after an optional `^`) - * `[][]` is a character set that will match either a close or an open bracket. - * or escape it with a backslash: `[[\]]` - * `[x-y]` matches exactly one character that is in the _range_ from `x` to `y` - * to include a literal hyphen character in a character set, it must be either the first character after the opening bracket (after an optional `^`) or the last character before the closing bracket. - * `[-xy]` or `[xy-]` each match exactly one character that is an `-` or a `x` or a `y` - * or escape it with a backslash: `[x\-y]` - * multiple ranges can be specified, for example `[0-9A-Fa-f]` matches a hexadecimal digit - * `[^abc]` matches exactly one character that is **NOT** an `a` or a `b` or a `c`, - * `[^x-y]` matches exactly one character that is **NOT** in the range from `x` to `y` - * `[[:character_class:]]` matches one character that is in the named "character_class" - * the available character classes are: - * `lower` -- lowercase letters - * `upper` -- uppercase letters - * `alpha` -- letters - * `digit` -- digits - * `alnum` -- letters and digits - * `space` -- whitespace - * `blank` -- horizontal whitespace (space and tab) - * `xdigit` -- hexadecimal digits - * `word` -- characters allowed in an identifier (letters, numbers, underscore) - * `punct` -- punctuation - * `cntrl` -- control characters - * `graph` -- "visible" characters - * `print` -- visible characters plus space - * they can be combined: - * the `[[:alpha:]]` class consists of `[[:lower:][:upper:]]` - * the `[[:alnum:]]` class consists of `[[:alpha:][:digit:]]` - * the `[[:word:]]` class consists of `[[:alnum:]_]` - * underscore (octal 137) is both `[[:word:]]` and `[[:punct:]]` - * the `[[:graph:]]` class consists of `[[:alnum:][:punct:]]` - * the `[[:print:]]` class consists of `[[:graph:] ]` -- just space (octal 040) not any other whitespace. -
- ~~~~ +Glob patterns **are not** regular expressions. +For example, a glob must match the _entire_ filename, but a regular expression can match only part of a string. + +#### Filename Expansion Is Done by the Shell + +You have probably used globs with `ls`: + +```bash +ls *.md +``` + +Filename expansion is a feature of the _shell_, not of the `ls` program. +Before it runs `ls`, bash replaces the pattern with the names of the matching files. +If the directory contains `a.md` and `b.md`, then `ls` is run as `ls a.md b.md`: `ls` never sees the `*`. +Every command gets the same treatment, which is why `echo *.md` prints the file names too. + +#### Quoting Part of a Pattern + +Quotes can cover just part of a word. +This lets you write a pattern in your script while keeping a variable's value literal: + +```bash +extension='md' +echo "*.$extension" # prints *.md +echo *."$extension" # prints a list of Markdown files +``` + +In the last line, the unquoted `*` is expanded by the shell. +The characters in `$extension` are quoted, so they are never split into words or treated as wildcards, whatever the value contains. #### Iterating Over a List of Files @@ -183,45 +145,40 @@ Note that the variable `"$file"` is quoted. The glob pattern can return files that contain spaces in the name. We need to quote the variable so that the `do_something_with` command receives exactly one argument, the file name. -#### Glob Patterns Are Not Regular Expressions - -Glob patterns **are not** regular expressions. - -* match exactly one character - * regex `.` - * glob `?` -* match zero or more characters - * regex `.*` - * glob `*` - * the glob pattern `.*` means "match a filename where the first character is a literal dot followed by zero or more of any characters". -* match one or more characters - * regex `.+` - * glob `?*` -* regex character sets and glob character sets act the same way. - -~~~~exercism/advanced -Bash provides [extended patterns][extended-patterns] that are closer to regular expressions. - -[extended-patterns]: https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching -~~~~ - #### Quoting and Filename Expansion There are times when you want to suppress filename expansion. Handling user input is one such time. -Consider this code snippet +This script is meant to repeat the user's answer back to them: ```bash -read -p "Enter something: " user_input -echo $user_input +read -p "What is your favourite punctuation mark? " mark +echo You chose: $mark +``` + +If the user enters an asterisk (`*`), the script should print `You chose: *`. +Instead, because `$mark` is not quoted, the shell replaces the asterisk with the names of the files in the current directory. +If that directory contains `a.md` and `b.md`, the output is + +```none +You chose: a.md b.md ``` -If the user enters an asterisk (`*`), what will be output? -The list of files in the current directory. -That's probably not what you want to do. +Quote the string to print exactly what the user entered: + +```bash +echo "You chose: $mark" +``` + +outputs + +```none +You chose: * +``` -Another example is to pass patterns as arguments to programs that expect patterns. -The `tr` program is often used for text manipulation. To lowercase a variable value, you can do this +Another example is when a program takes literal patterns as arguments. +The `tr` program is often used for text manipulation. +To lowercase a variable value, you can do this: ```bash var="My Puppet" @@ -235,9 +192,12 @@ my puppet A common mistake is to forget to quote `tr`'s arguments: `tr [:upper:] [:lower:]` ~~~~exercism/caution -Why is that a problem? -Unquoted glob patterns will be expanded to the list of files that match. -Suppose the person using your script has a files named `p` and `u` and `w` in the current directory: +Why is that a problem? +To the shell, an unquoted `[:upper:]` is a glob pattern that matches a file whose name is one of the characters `:`, `u`, `p`, `e` or `r`. +Likewise, `[:lower:]` matches a file named `:`, `l`, `o`, `w`, `e` or `r`. + +If no files match, bash leaves the patterns unchanged by default, and the command works. +But suppose the person using your script has files named `p`, `u` and `w` in the current directory: ```bash touch p u w @@ -245,42 +205,14 @@ var="My Puppet" echo "$var" | tr [:upper:] [:lower:] ``` -This results in an error! - -The unquoted `[:upper:]` pattern matches any of `:`, `u`, `p`, `e` or `r`. -The unquoted `[:lower:]` pattern matches any of `:`, `l`, `o`, `w`, `e` or `r`. -Bash matches the files `p` and `u` for the first pattern, and the file `w` for the second pattern, and `tr` is invoked like +Bash replaces the first pattern with `p u` and the second with `w`, so it runs this instead: ```bash echo "$var" | tr p u w ``` -And that's the wrong number of arguments for `tr`. +`tr` fails with an error because it received three arguments instead of two. ~~~~ -#### Disable Filename Expansion - -You can use the [`set`][set] command to disable filename expansion. - -```bash -echo * # prints a list of files -set -f # disable filename expansion -echo * # prints a literal asterisk -set +f # enable filename expansion -``` - -#### Controlling Filename Expansion - -There are several settings for the builtin [`shopt`][shopt] command that control how filename expansion operates. -A couple of interesting ones are: - -* `shopt -s nocaseglob` -- perform case insensitive matching -* `shopt -s extglob` -- enable extended patterns -* `shopt -s nullglob` -- if no files match, replace the pattern with nothing. - The default behaviour is to leave the pattern in place as a literal string. - - [expansions]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions [glob]: https://en.wikipedia.org/wiki/Glob_(programming) -[set]: https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin -[shopt]: https://www.gnu.org/software/bash/manual/bash.html#The-Shopt-Builtin diff --git a/config.json b/config.json index 3cee2be2..00d988d4 100644 --- a/config.json +++ b/config.json @@ -55,6 +55,18 @@ "commands-and-arguments" ], "status": "wip" + }, + { + "slug": "messy-downloads", + "name": "Messy Downloads", + "uuid": "65f92a90-3b28-4498-b9ad-5649acc484f3", + "concepts": [ + "quoting" + ], + "prerequisites": [ + "variables" + ], + "status": "wip" } ], "practice": [ diff --git a/exercises/concept/messy-downloads/.docs/hints.md b/exercises/concept/messy-downloads/.docs/hints.md new file mode 100644 index 00000000..966b3533 --- /dev/null +++ b/exercises/concept/messy-downloads/.docs/hints.md @@ -0,0 +1,40 @@ +# Hints + +## General + +- Quote your parameter expansions: `"$name"`. +- Double quotes allow expansions; single quotes do not. +- Read the [Quoting][quoting] section of the Bash manual, or the track's quoting concept page. + +## 1. Print the name of the file you are looking at + +- Use [`echo`][echo] with a double-quoted string that contains the variable. +- Put a backslash before a double quote to include it literally inside a double-quoted string: `"She said \"hi\""`. + +## 2. Print the contents of the file + +- `cat file` prints the contents of the file. +- If the file name contains a space and the variable is not quoted, `cat` receives two arguments instead of one. + +## 3. Print a reminder + +- Single quotes keep every character literal, including `*` and `$`. + +## 4. Print the pattern and the files it matches + +- An unquoted `*.txt` is replaced by the names of the matching files before `echo` runs. +- Inside double quotes, `*` is literal but a variable is still expanded. +- To list the matching files, leave the `*` _unquoted_ so that the shell expands the pattern. + The shell does not split a file name that contains spaces: each matching file is one argument. +- Quotes can cover just part of a word: quote the variable, but not the `*`. +- To print one name per line, you can use a `for` loop over the pattern, or `printf '%s\n'`. +- `printf '%s\n' one two` prints `one` and `two` on separate lines: the format is reused for each argument. +- In a `for` loop, quote the loop variable: `"$file"`. + +## 5. Print the note + +- Without quotes, the shell splits the value into words, and `echo` joins them with single spaces. +- Quote the expansion to keep the value exactly as it was given. + +[quoting]: https://www.gnu.org/software/bash/manual/bash.html#Quoting +[echo]: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins diff --git a/exercises/concept/messy-downloads/.docs/instructions.md b/exercises/concept/messy-downloads/.docs/instructions.md new file mode 100644 index 00000000..36d92147 --- /dev/null +++ b/exercises/concept/messy-downloads/.docs/instructions.md @@ -0,0 +1,85 @@ +# Instructions + +Your downloads folder is a mess. +Some of the files have spaces in their names, some have square brackets, and you are nervous about running commands that might expand something you did not intend. + +You are going to write a script that inspects one file safely. +Each task adds to the same script, so preserve the output from the previous tasks. +Do not print anything other than the requested output. + +The script accepts three command-line arguments: + +1. the name of a file in the current directory. + The name may contain spaces or other unusual characters. +2. a file extension without the dot, such as `txt`. +3. a short note, which may contain repeated spaces. + +You learned about positional parameters (`$1`, `$2`, and so on) in the [Variables][variables] concept. +They hold these three arguments. + +Run the script with: + +```bash +bash messy_downloads.sh 'my report.txt' 'txt' 'keep these spaces' +``` + +The examples below assume the current directory contains these files: + +- `a.txt` +- `b.txt` +- `my report.txt`, which contains `hello downloads` +- `notes [v2].txt` + +## 1. Print the name of the file you are looking at + +Print `Looking at` followed by the name of the file, surrounded by double quotes: + +```text +Looking at "my report.txt" +``` + +## 2. Print the contents of the file + +Use `cat` to print the contents of the file given as the first argument. + +```text +hello downloads +``` + +## 3. Print a reminder + +Print the following reminder exactly as shown. +The `*` and the `$HOME` must appear literally: nothing in the line should be expanded. + +```text +Careful: rm * deletes everything and $HOME is your home directory +``` + +## 4. Print the pattern and the files it matches + +The second argument is a file extension. +Print the pattern for files with that extension, after the word `Pattern:`. +The pattern is `*.` followed by the extension, and it must be printed literally, not replaced by the names of the files that match it. + +Then print the files that the pattern matches, one per line. +This time you _want_ the shell to expand the `*`. +The extension must still be taken literally, even if it contains spaces or wildcard characters. + +```text +Pattern: *.txt +a.txt +b.txt +my report.txt +notes [v2].txt +``` + +## 5. Print the note + +Print the note from the third argument, after the word `Note:`. +Repeated spaces in the note must be preserved. + +```text +Note: keep these spaces +``` + +[variables]: https://exercism.org/tracks/bash/concepts/variables diff --git a/exercises/concept/messy-downloads/.docs/introduction.md b/exercises/concept/messy-downloads/.docs/introduction.md new file mode 100644 index 00000000..23da5b4f --- /dev/null +++ b/exercises/concept/messy-downloads/.docs/introduction.md @@ -0,0 +1,220 @@ +# Introduction + +## The Importance of Quoting + +One piece of advice new bash programmers will hear over and over: + +> Quote your variables! + +Why is that? + +When you expand a variable (like `$name`) you almost always want to use the _value_ of the variable as a single string (or number). +You don't want the value to be unexpectedly handled as two or more separate strings. + +### Quoting + +Quoting is the primary mechanism to ensure that a piece of text is treated as a single word. +There are two main types of quotes. + +#### Double Quotes + +Double quotes allow parameter expansion, arithmetic expansion and command substitution within them. + +```bash +echo "This is bash version $BASH_VERSION" +``` + +You can include a literal double quote inside a double-quoted string by preceding it with a backslash. + +```bash +echo "She said \"Let me teach you about bash.\"" +``` + +#### Single quotes + +Single quotes _do not allow_ any expansions inside them. + +```bash +echo 'This is bash version $BASH_VERSION' +# ...^..................................^ +# prints exactly: This is bash version $BASH_VERSION +``` + +It is _not possible_ to embed a single quote inside a single-quoted string. + +### Importance of quoting + +What's wrong with `echo $name`, exactly? + +When the shell parses a line of code, it performs [several kinds of expansions][expansions], in order. +Two of the last expansions are _Word Splitting_ and _Filename Expansion_. + +#### Word Splitting + +Any results of parameter expansion, command substitution or arithmetic expansion _that did not occur within double quotes_ are eligible for "word splitting". +The shell splits the expanded result into separate words on spaces, tabs and newlines. + +The `printf '%s\n'` command prints each of its arguments on a line of its own, so it shows how many words a command receives: + +```bash +sentence="The quick brown fox jumps." +printf '%s\n' "$sentence" +``` +outputs +```none +The quick brown fox jumps. +``` + +But unquoted: + +```bash +printf '%s\n' $sentence +``` +outputs +```none +The +quick +brown +fox +jumps. +``` + +##### Preserving Whitespace + +Recall from the introduction to Commands and Arguments that quotes preserve repeated whitespace. +This also applies to variables. +Unquoted, the value is split into words, and `echo` joins those words with single spaces. + +```bash +message="two spaces" +echo $message # prints: two spaces +echo "$message" # prints: two spaces +``` + +#### Filename Expansion + +"Glob" patterns are used to express a concise pattern to match a set of files. +For example, you might match all the Markdown files in a directory with `*.md`. +[Glob patterns][glob] have existed since the invention of Unix. + +The glob wildcard characters are: + +* `*` matches zero or more of any character, +* `?` matches exactly one of any character, +* `[...]` matches exactly one character from the set of characters listed inside the brackets. + +Glob patterns **are not** regular expressions. +For example, a glob must match the _entire_ filename, but a regular expression can match only part of a string. + +##### Filename Expansion Is Done by the Shell + +You have probably used globs with `ls`: + +```bash +ls *.md +``` + +Filename expansion is a feature of the _shell_, not of the `ls` program. +Before it runs `ls`, bash replaces the pattern with the names of the matching files. +If the directory contains `a.md` and `b.md`, then `ls` is run as `ls a.md b.md`: `ls` never sees the `*`. +Every command gets the same treatment, which is why `echo *.md` prints the file names too. + +##### Quoting Part of a Pattern + +Quotes can cover just part of a word. +This lets you write a pattern in your script while keeping a variable's value literal: + +```bash +extension='md' +echo "*.$extension" # prints *.md +echo *."$extension" # prints a list of Markdown files +``` + +In the last line, the unquoted `*` is expanded by the shell. +The characters in `$extension` are quoted, so they are never split into words or treated as wildcards, whatever the value contains. + +##### Iterating Over a List of Files + +You can iterate over a list of files with a `for` loop + +```bash +for file in *.csv; do + do_something_with "$file" +done +``` + +Note that the variable `"$file"` is quoted. +The glob pattern can return files that contain spaces in the name. +We need to quote the variable so that the `do_something_with` command receives exactly one argument, the file name. + +##### Quoting and Filename Expansion + +There are times when you want to suppress filename expansion. +Handling user input is one such time. +This script is meant to repeat the user's answer back to them: + +```bash +read -p "What is your favourite punctuation mark? " mark +echo You chose: $mark +``` + +If the user enters an asterisk (`*`), the script should print `You chose: *`. +Instead, because `$mark` is not quoted, the shell replaces the asterisk with the names of the files in the current directory. +If that directory contains `a.md` and `b.md`, the output is + +```none +You chose: a.md b.md +``` + +Quote the string to print exactly what the user entered: + +```bash +echo "You chose: $mark" +``` + +outputs + +```none +You chose: * +``` + +Another example is when a program takes literal patterns as arguments. +The `tr` program is often used for text manipulation. +To lowercase a variable value, you can do this: + +```bash +var="My Puppet" +echo "$var" | tr '[:upper:]' '[:lower:]' +``` +outputs +```none +my puppet +``` + +A common mistake is to forget to quote `tr`'s arguments: `tr [:upper:] [:lower:]` + +~~~~exercism/caution +Why is that a problem? +To the shell, an unquoted `[:upper:]` is a glob pattern that matches a file whose name is one of the characters `:`, `u`, `p`, `e` or `r`. +Likewise, `[:lower:]` matches a file named `:`, `l`, `o`, `w`, `e` or `r`. + +If no files match, bash leaves the patterns unchanged by default, and the command works. +But suppose the person using your script has files named `p`, `u` and `w` in the current directory: + +```bash +touch p u w +var="My Puppet" +echo "$var" | tr [:upper:] [:lower:] +``` + +Bash replaces the first pattern with `p u` and the second with `w`, so it runs this instead: + +```bash +echo "$var" | tr p u w +``` + +`tr` fails with an error because it received three arguments instead of two. +~~~~ + +[expansions]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions +[glob]: https://en.wikipedia.org/wiki/Glob_(programming) diff --git a/exercises/concept/messy-downloads/.docs/introduction.md.tpl b/exercises/concept/messy-downloads/.docs/introduction.md.tpl new file mode 100644 index 00000000..a8db19c5 --- /dev/null +++ b/exercises/concept/messy-downloads/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:quoting} diff --git a/exercises/concept/messy-downloads/.meta/config.json b/exercises/concept/messy-downloads/.meta/config.json new file mode 100644 index 00000000..e429895c --- /dev/null +++ b/exercises/concept/messy-downloads/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "messy_downloads.sh" + ], + "test": [ + "messy_downloads.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "blurb": "Learn about quoting by tidying up a downloads folder full of awkwardly named files." +} diff --git a/exercises/concept/messy-downloads/.meta/design.md b/exercises/concept/messy-downloads/.meta/design.md new file mode 100644 index 00000000..7ddb1ba3 --- /dev/null +++ b/exercises/concept/messy-downloads/.meta/design.md @@ -0,0 +1,36 @@ +# Design + +## Goal + +The goal of this exercise is to introduce quoting in Bash scripts. + +## Learning objectives + +- Use double quotes to include a variable's value in a string. +- Embed literal double quotes inside a double-quoted string with a backslash. +- Use single quotes to prevent every expansion. +- Quote parameter expansions so a value containing spaces stays a single word. +- Quote parameter expansions so glob characters in a value are not expanded to file names. +- See the effect of quoting, by contrasting a quoted pattern with one where the unquoted `*` expands to file names. +- Quote part of a word, so a wildcard is expanded while a variable's value stays literal. +- Know that quoting preserves repeated whitespace. + +## Out of scope + +- Changing `IFS`. +- Disabling filename expansion with `set -f` or tuning it with `shopt`. +- Extended glob patterns and character-class details. +- Embedding a single quote in a single-quoted string, and `$'...'` quoting. +- Requiring loops: students may use one to list the matching files, as previewed in the introduction, but it is not a learning objective. +- Practicing quoting inside arrays and `[[ ]]` tests. +- Practicing quoting in pipelines, such as the arguments of `tr` (the introduction shows this as an example). + +## Concepts + +The Concepts this exercise unlocks are: + +- `quoting` + +## Prerequisites + +- `variables` diff --git a/exercises/concept/messy-downloads/.meta/exemplar.sh b/exercises/concept/messy-downloads/.meta/exemplar.sh new file mode 100644 index 00000000..4b8c61cc --- /dev/null +++ b/exercises/concept/messy-downloads/.meta/exemplar.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +file=$1 +extension=$2 +note=$3 + +# Task 1 +echo "Looking at \"${file}\"" + +# Task 2 +cat "$file" + +# Task 3 +# shellcheck disable=SC2016 +echo 'Careful: rm * deletes everything and $HOME is your home directory' + +# Task 4 +echo "Pattern: *.${extension}" +# Only the * is unquoted, so only the * is expanded. +printf '%s\n' *."$extension" + +# Task 5 +echo "Note: ${note}" diff --git a/exercises/concept/messy-downloads/bats-extra.bash b/exercises/concept/messy-downloads/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/messy-downloads/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/messy-downloads/messy_downloads.bats b/exercises/concept/messy-downloads/messy_downloads.bats new file mode 100644 index 00000000..417d68a0 --- /dev/null +++ b/exercises/concept/messy-downloads/messy_downloads.bats @@ -0,0 +1,132 @@ +#!/usr/bin/env bats +load bats-extra +declare lines + +# Each test runs in a fresh "downloads" directory that contains +# several files, some with awkward names. +setup() { + cd "$BATS_TEST_TMPDIR" || return 1 + printf 'hello downloads\n' > 'my report.txt' + printf 'second file\n' > 'notes [v2].txt' + printf 'plain\n' > 'a.txt' + printf 'plain\n' > 'b.txt' + printf 'plain\n' > 'c.md' + printf 'plain\n' > 'old.[1]' + printf 'plain\n' > 'old.1' + script="${BATS_TEST_DIRNAME}/messy_downloads.sh" +} + +# bats test_tags=task:1 +test_looking_at_file_with_spaces() { # @test + run bash "$script" 'my report.txt' 'txt' 'note' + + assert_success + assert_line --index 0 'Looking at "my report.txt"' +} + +# bats test_tags=task:1 +test_looking_at_file_with_brackets() { # @test + run bash "$script" 'notes [v2].txt' 'txt' 'note' + + assert_success + assert_line --index 0 'Looking at "notes [v2].txt"' +} + +# bats test_tags=task:2 +test_contents_of_file_with_spaces() { # @test + run bash "$script" 'my report.txt' 'txt' 'note' + + assert_success + assert_line --index 1 'hello downloads' +} + +# bats test_tags=task:2 +test_contents_of_file_with_brackets() { # @test + run bash "$script" 'notes [v2].txt' 'txt' 'note' + + assert_success + assert_line --index 1 'second file' +} + +# bats test_tags=task:3 +test_reminder() { # @test + run bash "$script" 'my report.txt' 'txt' 'note' + + assert_success + # shellcheck disable=SC2016 + assert_line --index 2 'Careful: rm * deletes everything and $HOME is your home directory' +} + +# bats test_tags=task:4 +test_pattern_is_not_expanded() { # @test + run bash "$script" 'my report.txt' 'txt' 'note' + + assert_success + assert_line --index 3 'Pattern: *.txt' +} + +# bats test_tags=task:4 +test_other_pattern_is_not_expanded() { # @test + run bash "$script" 'my report.txt' 'md' 'note' + + assert_success + assert_line --index 3 'Pattern: *.md' +} + +# bats test_tags=task:4 +test_pattern_matches_are_listed() { # @test + run bash "$script" 'my report.txt' 'txt' 'note' + + assert_success + assert_line --index 4 'a.txt' + assert_line --index 5 'b.txt' + assert_line --index 6 'my report.txt' + assert_line --index 7 'notes [v2].txt' +} + +# bats test_tags=task:4 +test_other_pattern_matches_are_listed() { # @test + run bash "$script" 'my report.txt' 'md' 'note' + + assert_success + assert_line --index 4 'c.md' + # 5 lines if task 5 is not done yet, 6 if it is. + # `assert` needs a command, so use `[` here. + assert [ "${#lines[@]}" -ge 5 ] + assert [ "${#lines[@]}" -le 6 ] +} + +# bats test_tags=task:4 +test_extension_is_taken_literally() { # @test + run bash "$script" 'my report.txt' '[1]' 'note' + + assert_success + assert_line --index 4 'old.[1]' + refute_line 'old.1' +} + +# bats test_tags=task:5 +test_note_keeps_its_spaces() { # @test + run bash "$script" 'my report.txt' 'txt' 'keep these spaces' + + assert_success + assert_line --index 8 'Note: keep these spaces' +} + +# bats test_tags=task:5 +test_exact_output() { # @test + run bash "$script" 'my report.txt' 'txt' 'two spaces' + + assert_success + assert_output - <<'END' +Looking at "my report.txt" +hello downloads +Careful: rm * deletes everything and $HOME is your home directory +Pattern: *.txt +a.txt +b.txt +my report.txt +notes [v2].txt +Note: two spaces +END +} diff --git a/exercises/concept/messy-downloads/messy_downloads.sh b/exercises/concept/messy-downloads/messy_downloads.sh new file mode 100644 index 00000000..a353b0bb --- /dev/null +++ b/exercises/concept/messy-downloads/messy_downloads.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# This script helps you tidy up a messy downloads folder. +# +# Arguments: +# $1 the name of a file in the current directory. +# The name may contain spaces or other unusual characters. +# $2 a file extension without the dot, such as txt +# $3 a short note, which may contain repeated spaces. +# +# Add your code below each task comment. +# Each task builds on the previous tasks, so keep the earlier output unchanged. +# Think about which quotes each task needs. + +# Task 1: print the name of the file you are looking at, +# surrounded by double quotes. + +# Task 2: print the contents of the file. + +# Task 3: print the reminder about dangerous characters. + +# Task 4: print the pattern for the file extension, +# then print the files that the pattern matches. + +# Task 5: print the note.