From 00135c6c7ac891cadc2ad440ea4ff24fa7f8e1a9 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sat, 21 Nov 2026 16:50:21 -0500 Subject: [PATCH 1/7] Add the lasagna concept exercise for variables - New wip concept exercise teaching variables with the Lasagna story: assignment, expansion, positional parameters, default values and command substitution, using expr for arithmetic. - Trim concepts/variables/introduction.md to what the exercise teaches; the full material remains in about.md. - Register the exercise in config.json. Co-Authored-By: Claude Sonnet 5.5 --- POLICIES.md | 6 + concepts/variables/introduction.md | 121 +--- config.json | 16 +- exercises/concept/lasagna/.docs/hints.md | 38 ++ .../concept/lasagna/.docs/instructions.md | 73 ++ .../concept/lasagna/.docs/introduction.md | 117 ++++ .../concept/lasagna/.docs/introduction.md.tpl | 29 + exercises/concept/lasagna/.meta/config.json | 20 + exercises/concept/lasagna/.meta/design.md | 33 + exercises/concept/lasagna/.meta/exemplar.sh | 26 + exercises/concept/lasagna/bats-extra.bash | 642 ++++++++++++++++++ exercises/concept/lasagna/lasagna.bats | 87 +++ exercises/concept/lasagna/lasagna.sh | 26 + 13 files changed, 1134 insertions(+), 100 deletions(-) create mode 100644 exercises/concept/lasagna/.docs/hints.md create mode 100644 exercises/concept/lasagna/.docs/instructions.md create mode 100644 exercises/concept/lasagna/.docs/introduction.md create mode 100644 exercises/concept/lasagna/.docs/introduction.md.tpl create mode 100644 exercises/concept/lasagna/.meta/config.json create mode 100644 exercises/concept/lasagna/.meta/design.md create mode 100644 exercises/concept/lasagna/.meta/exemplar.sh create mode 100644 exercises/concept/lasagna/bats-extra.bash create mode 100644 exercises/concept/lasagna/lasagna.bats create mode 100644 exercises/concept/lasagna/lasagna.sh diff --git a/POLICIES.md b/POLICIES.md index 18c66747..7fad6cb4 100644 --- a/POLICIES.md +++ b/POLICIES.md @@ -32,6 +32,12 @@ Markdown documents in this repository should use "ventilated prose": one sentenc 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. +### Markdown style + +Markdown documents in this repository should use "ventilated prose": one sentence per line. +This keeps diffs focused on the sentences that actually changed, which makes code review easier. +Additionally, ensure that both headers and lists have a blank line before and after them. + ### Prefer standard bash over POSIX compliance When submitting or updating exercises, POSIX compliance is not required. diff --git a/concepts/variables/introduction.md b/concepts/variables/introduction.md index 13534020..46cb518e 100644 --- a/concepts/variables/introduction.md +++ b/concepts/variables/introduction.md @@ -1,12 +1,8 @@ # Introduction to Variables -## Variables - _Variables_ are a place to hold data. -Bash has two kinds of data: strings and arrays. -We'll talk about arrays later. - You assign a variable like this + ```bash name="value" ``` @@ -23,19 +19,6 @@ x = 10 bash is going to call the **command** `x` with the **two arguments** `=` and `10`! ~~~~ -Variables can also be called _parameters_. -The two terms will be used interchangably in this document. - -Some important parameters used by or set by bash include: - -* `PATH` -- a colon-separated list of directories used to find external commands. -* `IFS` -- the "internal field separator". - We'll see how it's used below. -* `PWD` -- your current working directory. - It will be the same value as the output of the `pwd` command. -* `RANDOM` -- a pseudo-random integer between 0 and 32767. -* `BASH_VERSION` -- the version string of the running instance of bash. - ## Variable Names A variable name consists of _uppercase letters, lowercase letters, numbers and underscore_. @@ -43,122 +26,64 @@ It cannot start with a number. ~~~~exercism/caution It is best practice to **avoid using ALLCAPS variable names**. -The shell uses this convention for its parameters, and you don't want to accidentally overwrite shell parameters that have special meaning. -For example: [1][1], [2][2], [3][3] - -[1]: https://stackoverflow.com/q/27555060/7552 -[2]: https://stackoverflow.com/q/28310594/7552 -[3]: https://unix.stackexchange.com/q/114596/4667 +The shell uses this convention for its own variables, and you don't want to accidentally overwrite one that has a special meaning. ~~~~ ## Parameter Expansion -You get the value of a parameter with the `$varname` syntax. +You get the value of a variable with the `$varname` syntax. ```bash x=10 echo "The value of x is $x" ``` -To prevent the variable name from being confused with surrounding text, you can enclose the variable name in braces. -For example to print the string `10x10` +To prevent the variable name from being confused with surrounding text, enclose the variable name in braces. +For example, to print the string `10x10` ```bash echo "${x}x$x" -# or -echo "${x}x${x}" ``` -Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. - ## Positional Parameters As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. Bash scripts are no exception. -The arguments to the current instance of bash are called _positional parameters_. -They can be retrieved with these special parameters: - -* `$1` -- the first positional parameter -* `$2` ... `$9` -- subsequent parameters -* `${10}` ... -- double digits require braces. -* `$0` -- the name of the current script. - -Arguments to a shell function are also positional parameters, handled just like this. -We'll see more about functions in a later lesson. +The arguments to a script are called _positional parameters_. +You can retrieve them with `$1` (the first argument), `$2` (the second argument), and so on. -### Special Positional Parameters - -There are some _special parameters_ that help you work with the positional parameters. +```bash +# run as: bash greet.sh Alice Bob +echo "Hello, $1 and $2" +# => Hello, Alice and Bob +``` -* `$#` expands to the _number_ of positional parameters. -* `"$@"` expands to the list of all of the positional parameters, each as a separate word. -* `"$*"` expands to a single string of all the positional parameters joined together by a character. - * The join character is _the first character_ of the `$IFS` variable, which is a space by default. +## Default Values -The `"$@"` is the safest way to pass positional parameters to another command while keeping them safely quoted. -It is also what you will use to loop over the positional parameters: +Use `${varname:-default}` to provide a default value when the variable is empty or unset. +This is useful for arguments that may be missing. ```bash -for arg in "$@"; do - do_something_with "$arg" -done +name=${1:-world} +echo "Hello, $name" +# => Hello, world (when the script is given no arguments) ``` -In practice, `"$@"` is used more often than `"$*"`. - ## Command Substitution A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. -To do this, you will use _command substitution_. +To do this, use _command substitution_. ```bash var=$(command) ``` -For example, to upper-case a string, you can do this: +For example: ```bash -text="Hello world!" -uppercase=$(echo "$text" | tr '[:lower:]' '[:upper:]') -echo "$uppercase" -# => HELLO WORLD! +kernel=$(uname -s) +echo "Running on $kernel" +# => Running on Linux ``` -## More on Parameter Expansion - -Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. - -* Uppercasing text. - In the previous section I showed how to use `tr` to upper case some text. - To do it in bash: - - ```bash - echo "${text^^}" - ``` - - Similarly, `${text,,}` lowercases the value. - -* Provide a default value if the variable is empty. - - ```bash - default="nothing here" - result="" - echo "${result:-$default}" - # => nothing here - ``` - -* Search and replace. - - ```bash - text="Hello world!" - echo "${text//[aeiou]/X}" - # => HXllX wXrld!" - ``` - -There are many other interesting parameter expansions: extract a substring, get the string length, _assign_ a default value, remove text from the start or end of the value, and more. -Read about them [in the manual][param-exp]. - - -[google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments -[param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion diff --git a/config.json b/config.json index 84af5f21..3cee2be2 100644 --- a/config.json +++ b/config.json @@ -43,6 +43,18 @@ ], "prerequisites": [], "status": "wip" + }, + { + "slug": "lasagna", + "name": "Lucian's Luscious Lasagna", + "uuid": "0a182883-a62b-49b5-aa02-accc682b6d9a", + "concepts": [ + "variables" + ], + "prerequisites": [ + "commands-and-arguments" + ], + "status": "wip" } ], "practice": [ @@ -674,10 +686,10 @@ "practices": [], "prerequisites": [], "difficulty": 4, + "status": "wip", "topics": [ "dates" - ], - "status": "wip" + ] }, { "slug": "binary-search", diff --git a/exercises/concept/lasagna/.docs/hints.md b/exercises/concept/lasagna/.docs/hints.md new file mode 100644 index 00000000..ce690f34 --- /dev/null +++ b/exercises/concept/lasagna/.docs/hints.md @@ -0,0 +1,38 @@ +# Hints + +## General + +- There must be _no spaces_ around the `=` in a variable assignment. +- Use `$name` or `${name}` to get the value of a variable. +- Quote parameter expansions: `"$name"`. +- Use `${name:-default}` to provide a default value when a variable is empty or unset. +- Use good variable names: lowercase, and descriptive. + +## 1. Define the expected oven time in minutes + +- Assign the value to a variable, then use [`echo`][echo] with the variable inside a double-quoted string. +- Braces can separate the variable name from surrounding text: `"${name}text"`. + +## 2. Calculate the remaining oven time in minutes + +- The first command-line argument is the [positional parameter][positional] `$1`. +- Use a default value to handle a missing argument: `${1:-0}`. +- [Command substitution][cmd-subst] captures the output of a command: `result=$(command args)`. +- `expr 7 - 2` outputs `5`. + Give it the variables as arguments, in quotes. + +## 3. Calculate the preparation time in minutes + +- The second command-line argument is `$2`. +- Remember to provide a default for a missing argument. +- `expr` needs the multiplication operator to be quoted so that Bash does not treat it as a filename pattern: `expr "$a" '*' "$b"`. +- Store the minutes per layer in a variable, so the number 2 has a name. + +## 4. Calculate the total working time in minutes + +- `expr "$a" + "$b"` adds two numbers. +- You can reuse the variables you have already assigned. + +[echo]: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins +[positional]: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters +[cmd-subst]: https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution diff --git a/exercises/concept/lasagna/.docs/instructions.md b/exercises/concept/lasagna/.docs/instructions.md new file mode 100644 index 00000000..f8e19314 --- /dev/null +++ b/exercises/concept/lasagna/.docs/instructions.md @@ -0,0 +1,73 @@ +# Instructions + +In this exercise you're going to write some code to help you cook a brilliant lasagna from your favorite cookbook. + +You have four tasks, all related to the time spent cooking the lasagna. +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 two optional command-line arguments: + +1. the number of minutes the lasagna has _actually_ been in the oven. + If it is missing, use `0`. +2. the number of layers in the lasagna. + If it is missing, use `1`. + +Run the script with: + +```bash +bash lasagna.sh 18 3 +``` + +Bash does not yet have arithmetic in this syllabus, so you can use the external `expr` command to do the math, and command substitution to capture its result. +For example, `expr 7 - 2` outputs `5`. + +## 1. Define the expected oven time in minutes + +According to the cookbook, the expected oven time is 40 minutes. +Store this value in a variable, and print it: + +```text +Expected minutes in oven: 40 +``` + +## 2. Calculate the remaining oven time in minutes + +Store the actual minutes in the oven (the first argument) in a variable. +Then calculate how many minutes the lasagna still has to remain in the oven, based on the expected oven time from the previous task. +Print it on the next line: + +```bash +bash lasagna.sh 18 3 +``` + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +``` + +## 3. Calculate the preparation time in minutes + +The preparation time is how long it takes to get the lasagna ready before it is put in the oven. +It takes 2 minutes to prepare each layer. +Store the number of layers (the second argument) in a variable, and store the minutes per layer in another variable instead of using a "magic number". +Print the preparation time on the next line: + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +Preparation time in minutes: 6 +``` + +## 4. Calculate the total working time in minutes + +Calculate how many minutes in total you've worked on cooking the lasagna. +This is the sum of the preparation time and the time the lasagna has spent in the oven so far. +Print it on the last line: + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +Preparation time in minutes: 6 +Total time in minutes: 24 +``` diff --git a/exercises/concept/lasagna/.docs/introduction.md b/exercises/concept/lasagna/.docs/introduction.md new file mode 100644 index 00000000..64f99ab7 --- /dev/null +++ b/exercises/concept/lasagna/.docs/introduction.md @@ -0,0 +1,117 @@ +# Introduction + +## Variables + +_Variables_ are a place to hold data. +You assign a variable like this + +```bash +name="value" +``` + +~~~~exercism/note +**Important** -- there must be _no spaces_ around the equal sign! + +When there are spaces, like in this example, + +```bash +x = 10 +``` + +bash is going to call the **command** `x` with the **two arguments** `=` and `10`! +~~~~ + +### Variable Names + +A variable name consists of _uppercase letters, lowercase letters, numbers and underscore_. +It cannot start with a number. + +~~~~exercism/caution +It is best practice to **avoid using ALLCAPS variable names**. +The shell uses this convention for its own variables, and you don't want to accidentally overwrite one that has a special meaning. +~~~~ + +### Parameter Expansion + +You get the value of a variable with the `$varname` syntax. + +```bash +x=10 +echo "The value of x is $x" +``` + +To prevent the variable name from being confused with surrounding text, enclose the variable name in braces. +For example, to print the string `10x10` + +```bash +echo "${x}x$x" +``` + +### Positional Parameters + +As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. +Bash scripts are no exception. +The arguments to a script are called _positional parameters_. +You can retrieve them with `$1` (the first argument), `$2` (the second argument), and so on. + +```bash +# run as: bash greet.sh Alice Bob +echo "Hello, $1 and $2" +# => Hello, Alice and Bob +``` + +### Default Values + +Use `${varname:-default}` to provide a default value when the variable is empty or unset. +This is useful for arguments that may be missing. + +```bash +name=${1:-world} +echo "Hello, $name" +# => Hello, world (when the script is given no arguments) +``` + +### Command Substitution + +A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. +To do this, use _command substitution_. + +```bash +var=$(command) +``` + +For example: + +```bash +kernel=$(uname -s) +echo "Running on $kernel" +# => Running on Linux +``` + +## Arithmetic with `expr` + +Bash has its own way to do arithmetic, which you will learn about later. +For now, you can use the external `expr` command. +It takes the numbers and the operator as separate arguments, so each must be a separate word, and it prints the result: + +```bash +expr 7 - 2 +# => 5 +``` + +Combine it with command substitution to store the result in a variable. +Remember that quoting your variable expansions keeps each value as a single argument: + +```bash +total=$(expr "$a" + "$b") +``` + +Some operators have a special meaning to Bash. +For example, an unquoted `*` is a filename pattern, which Bash replaces with the names of the files in the current directory. +Quote such an operator so that `expr` receives it as an argument: + +```bash +product=$(expr "$a" '*' "$b") +``` + +[cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments diff --git a/exercises/concept/lasagna/.docs/introduction.md.tpl b/exercises/concept/lasagna/.docs/introduction.md.tpl new file mode 100644 index 00000000..30e20910 --- /dev/null +++ b/exercises/concept/lasagna/.docs/introduction.md.tpl @@ -0,0 +1,29 @@ +# Introduction + +%{concept:variables} + +## Arithmetic with `expr` + +Bash has its own way to do arithmetic, which you will learn about later. +For now, you can use the external `expr` command. +It takes the numbers and the operator as separate arguments, so each must be a separate word, and it prints the result: + +```bash +expr 7 - 2 +# => 5 +``` + +Combine it with command substitution to store the result in a variable. +Remember that quoting your variable expansions keeps each value as a single argument: + +```bash +total=$(expr "$a" + "$b") +``` + +Some operators have a special meaning to Bash. +For example, an unquoted `*` is a filename pattern, which Bash replaces with the names of the files in the current directory. +Quote such an operator so that `expr` receives it as an argument: + +```bash +product=$(expr "$a" '*' "$b") +``` diff --git a/exercises/concept/lasagna/.meta/config.json b/exercises/concept/lasagna/.meta/config.json new file mode 100644 index 00000000..c867315b --- /dev/null +++ b/exercises/concept/lasagna/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "lasagna.sh" + ], + "test": [ + "lasagna.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "blurb": "Learn about variables by keeping track of the time spent cooking a lasagna." +} diff --git a/exercises/concept/lasagna/.meta/design.md b/exercises/concept/lasagna/.meta/design.md new file mode 100644 index 00000000..fcf59041 --- /dev/null +++ b/exercises/concept/lasagna/.meta/design.md @@ -0,0 +1,33 @@ +# Design + +## Goal + +The goal of this exercise is to introduce variables in Bash scripts. + +## Learning objectives + +- Assign a value to a variable, with no spaces around the equal sign. +- Expand a variable's value with `$name` and `${name}`. +- Use descriptive, non-ALLCAPS variable names. +- Read command-line arguments through positional parameters. +- Provide a default value with `${name:-default}`. +- Capture the output of a command in a variable with command substitution. + +## Out of scope + +- Arithmetic expansion; `expr` is used instead. +- Arrays. +- Functions and `local` variables. +- Exported variables and the environment. +- Parameter expansions beyond default values. +- Conditionals and loops. + +## Concepts + +The Concepts this exercise unlocks are: + +- `variables` + +## Prerequisites + +- `commands-and-arguments` diff --git a/exercises/concept/lasagna/.meta/exemplar.sh b/exercises/concept/lasagna/.meta/exemplar.sh new file mode 100644 index 00000000..5e24db25 --- /dev/null +++ b/exercises/concept/lasagna/.meta/exemplar.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# `expr` is an external command that does simple arithmetic. +# Bash has a builtin way to do this, which a later concept will cover. +# shellcheck disable=SC2003 + +expected_minutes_in_oven=40 +minutes_per_layer=2 + +actual_minutes_in_oven=${1:-0} +number_of_layers=${2:-1} + +# Task 1 +echo "Expected minutes in oven: ${expected_minutes_in_oven}" + +# Task 2 +remaining_minutes_in_oven=$(expr "$expected_minutes_in_oven" - "$actual_minutes_in_oven") +echo "Remaining minutes in oven: ${remaining_minutes_in_oven}" + +# Task 3 +preparation_time=$(expr "$number_of_layers" '*' "$minutes_per_layer") +echo "Preparation time in minutes: ${preparation_time}" + +# Task 4 +total_time=$(expr "$preparation_time" + "$actual_minutes_in_oven") +echo "Total time in minutes: ${total_time}" diff --git a/exercises/concept/lasagna/bats-extra.bash b/exercises/concept/lasagna/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/lasagna/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/lasagna/lasagna.bats b/exercises/concept/lasagna/lasagna.bats new file mode 100644 index 00000000..5dbe2474 --- /dev/null +++ b/exercises/concept/lasagna/lasagna.bats @@ -0,0 +1,87 @@ +#!/usr/bin/env bats +load bats-extra + +# bats test_tags=task:1 +test_expected_minutes_in_oven() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 0 "Expected minutes in oven: 40" +} + +# bats test_tags=task:2 +test_remaining_minutes_in_oven() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 1 "Remaining minutes in oven: 22" +} + +# bats test_tags=task:2 +test_remaining_minutes_in_oven_other_value() { # @test + run bash lasagna.sh 30 3 + + assert_success + assert_line --index 1 "Remaining minutes in oven: 10" +} + +# bats test_tags=task:2 +test_remaining_minutes_defaults_to_zero_minutes_in_oven() { # @test + run bash lasagna.sh + + assert_success + assert_line --index 1 "Remaining minutes in oven: 40" +} + +# bats test_tags=task:3 +test_preparation_time() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 2 "Preparation time in minutes: 6" +} + +# bats test_tags=task:3 +test_preparation_time_other_value() { # @test + run bash lasagna.sh 18 5 + + assert_success + assert_line --index 2 "Preparation time in minutes: 10" +} + +# bats test_tags=task:3 +test_preparation_time_defaults_to_one_layer() { # @test + run bash lasagna.sh 18 + + assert_success + assert_line --index 2 "Preparation time in minutes: 2" +} + +# bats test_tags=task:4 +test_total_time() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 3 "Total time in minutes: 24" +} + +# bats test_tags=task:4 +test_total_time_with_defaults() { # @test + run bash lasagna.sh + + assert_success + assert_line --index 3 "Total time in minutes: 2" +} + +# bats test_tags=task:4 +test_exact_output() { # @test + run bash lasagna.sh 10 2 + + assert_success + assert_output - <<'END' +Expected minutes in oven: 40 +Remaining minutes in oven: 30 +Preparation time in minutes: 4 +Total time in minutes: 14 +END +} diff --git a/exercises/concept/lasagna/lasagna.sh b/exercises/concept/lasagna/lasagna.sh new file mode 100644 index 00000000..4f1bef45 --- /dev/null +++ b/exercises/concept/lasagna/lasagna.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# This script helps you keep track of the time spent making a lasagna. +# +# Arguments (both optional): +# $1 the actual number of minutes the lasagna has been in the oven. +# Default: 0 +# $2 the number of layers in the lasagna. +# Default: 1 +# +# Add your code below each task comment. +# Each task builds on the previous tasks, so keep the earlier output unchanged. +# Use variables to give names to the values you work with. + +# Task 1: define a variable for the expected oven time (in minutes) +# and print it. + +# Task 2: store the actual oven time from the first argument in a variable +# (using a default value if it is missing), +# then print the remaining oven time. + +# Task 3: store the number of layers from the second argument in a variable +# (using a default value if it is missing), +# then print the preparation time. + +# Task 4: print the total working time. From e6c532b4fa69b29c4b5efc6d7376999a53ecfea1 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Thu, 26 Nov 2026 18:59:01 -0500 Subject: [PATCH 2/7] Bash -> bash --- exercises/concept/lasagna/.docs/hints.md | 2 +- exercises/concept/lasagna/.docs/introduction.md.tpl | 4 ++-- exercises/concept/lasagna/.meta/design.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/exercises/concept/lasagna/.docs/hints.md b/exercises/concept/lasagna/.docs/hints.md index ce690f34..ec75b57e 100644 --- a/exercises/concept/lasagna/.docs/hints.md +++ b/exercises/concept/lasagna/.docs/hints.md @@ -25,7 +25,7 @@ - The second command-line argument is `$2`. - Remember to provide a default for a missing argument. -- `expr` needs the multiplication operator to be quoted so that Bash does not treat it as a filename pattern: `expr "$a" '*' "$b"`. +- `expr` needs the multiplication operator to be quoted so that bash does not treat it as a filename pattern: `expr "$a" '*' "$b"`. - Store the minutes per layer in a variable, so the number 2 has a name. ## 4. Calculate the total working time in minutes diff --git a/exercises/concept/lasagna/.docs/introduction.md.tpl b/exercises/concept/lasagna/.docs/introduction.md.tpl index 30e20910..40da1aa6 100644 --- a/exercises/concept/lasagna/.docs/introduction.md.tpl +++ b/exercises/concept/lasagna/.docs/introduction.md.tpl @@ -20,8 +20,8 @@ Remember that quoting your variable expansions keeps each value as a single argu total=$(expr "$a" + "$b") ``` -Some operators have a special meaning to Bash. -For example, an unquoted `*` is a filename pattern, which Bash replaces with the names of the files in the current directory. +Some operators have a special meaning to bash. +For example, an unquoted `*` is a filename pattern, which bash replaces with the names of the files in the current directory. Quote such an operator so that `expr` receives it as an argument: ```bash diff --git a/exercises/concept/lasagna/.meta/design.md b/exercises/concept/lasagna/.meta/design.md index fcf59041..dd8eecf2 100644 --- a/exercises/concept/lasagna/.meta/design.md +++ b/exercises/concept/lasagna/.meta/design.md @@ -2,7 +2,7 @@ ## Goal -The goal of this exercise is to introduce variables in Bash scripts. +The goal of this exercise is to introduce variables in bash scripts. ## Learning objectives From 1d694e79b6cce1ea94a5d1cefbd6340b27922fef Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sat, 28 Nov 2026 10:37:40 -0500 Subject: [PATCH 3/7] Use arithmetic expansion in the lasagna exercise - Introduce arithmetic expansion and "magic numbers" in the variables concept. - Replace expr with arithmetic expansion in the lasagna docs and exemplar. - In the arithmetic concept, refer back to the variables lesson instead of introducing arithmetic expansion again. - Restore the style guide advice about braces to the variables introduction. Co-Authored-By: Claude Sonnet 5.5 --- concepts/arithmetic/about.md | 23 +------- concepts/arithmetic/introduction.md | 23 +------- concepts/variables/about.md | 52 ++++++++++++++++++ concepts/variables/introduction.md | 55 +++++++++++++++++++ exercises/concept/lasagna/.docs/hints.md | 11 ++-- .../concept/lasagna/.docs/instructions.md | 4 +- .../concept/lasagna/.docs/introduction.md | 55 ++++++++++++++----- .../concept/lasagna/.docs/introduction.md.tpl | 26 --------- exercises/concept/lasagna/.meta/design.md | 3 +- exercises/concept/lasagna/.meta/exemplar.sh | 10 +--- 10 files changed, 165 insertions(+), 97 deletions(-) diff --git a/concepts/arithmetic/about.md b/concepts/arithmetic/about.md index 9aee746b..6872fdcd 100644 --- a/concepts/arithmetic/about.md +++ b/concepts/arithmetic/about.md @@ -9,31 +9,12 @@ Additionally, Bash only performs arithmetic in certain places (known as arithmet ## Arithmetic Expansion -Arithmetic expansion looks like [command substitution][cmd-sub], but with double parentheses. - -```bash -$(( expression )) -``` - -This syntax expands to the result of evaluating the expression. -It is commonly used to capture the result in a variable: - -```bash -x=$(( 3 + 4 )) -``` - -~~~~exercism/note -The amount of whitespace inside the parentheses is up to you. -It is a matter of style and readability. +As we saw in the [Variables][variables] lesson, math can be performed in an arithmetic expansion. ```bash x=$(( 3 + 4 )) -y=$((5+6)) ``` -Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. -~~~~ - ## Arithmetic Conditional The arithmetic conditional is performed within double parentheses _without_ the leading `$`: @@ -183,4 +164,4 @@ area=$(( $1 * $2 )) [let]: https://www.gnu.org/software/bash/manual/bash.html#index-let [awk]: https://www.gnu.org/software/gawk/manual/html_node/index.html [bc]: https://www.gnu.org/software/bc/manual/html_mono/bc.html -[cmd-sub]: https://exercism.org/tracks/bash/concepts/variables#h-command-substitution +[variables]: https://exercism.org/tracks/bash/concepts/variables#h-arithmetic-expansion diff --git a/concepts/arithmetic/introduction.md b/concepts/arithmetic/introduction.md index 54a63018..58de104a 100644 --- a/concepts/arithmetic/introduction.md +++ b/concepts/arithmetic/introduction.md @@ -9,31 +9,12 @@ Additionally, Bash only performs arithmetic in certain places (known as arithmet ## Arithmetic Expansion -Arithmetic expansion looks like [command substitution][cmd-sub], but with double parentheses. - -```bash -$(( expression )) -``` - -This syntax expands to the result of evaluating the expression. -It is commonly used to capture the result in a variable: - -```bash -x=$(( 3 + 4 )) -``` - -~~~~exercism/note -The amount of whitespace inside the parentheses is up to you. -It is a matter of style and readability. +As we saw in the [Variables][variables] lesson, math can be performed in an arithmetic expansion. ```bash x=$(( 3 + 4 )) -y=$((5+6)) ``` -Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. -~~~~ - ## Arithmetic Conditional The arithmetic conditional is performed within double parentheses _without_ the leading `$`: @@ -183,4 +164,4 @@ area=$(( $1 * $2 )) [let]: https://www.gnu.org/software/bash/manual/bash.html#index-let [awk]: https://www.gnu.org/software/gawk/manual/html_node/index.html [bc]: https://www.gnu.org/software/bc/manual/html_mono/bc.html -[cmd-sub]: https://exercism.org/tracks/bash/concepts/variables#h-command-substitution +[variables]: https://exercism.org/tracks/bash/concepts/variables#h-arithmetic-expansion diff --git a/concepts/variables/about.md b/concepts/variables/about.md index ed1d8962..79796784 100644 --- a/concepts/variables/about.md +++ b/concepts/variables/about.md @@ -124,6 +124,58 @@ echo "$uppercase" # => HELLO WORLD! ``` +## Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` + +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: + +```bash +x=$(( 3 + 4 )) +``` + +Inside the parentheses, you can use a variable's name without the `$`: + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. + +```bash +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +## Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) +``` + ## More on Parameter Expansion Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. diff --git a/concepts/variables/introduction.md b/concepts/variables/introduction.md index 46cb518e..84979bf5 100644 --- a/concepts/variables/introduction.md +++ b/concepts/variables/introduction.md @@ -45,6 +45,8 @@ For example, to print the string `10x10` echo "${x}x$x" ``` +Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. + ## Positional Parameters As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. @@ -86,4 +88,57 @@ echo "Running on $kernel" # => Running on Linux ``` +## Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` + +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: + +```bash +x=$(( 3 + 4 )) +``` + +Inside the parentheses, you can use a variable's name without the `$`: + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. + +```bash +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +## Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) +``` + +[google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments diff --git a/exercises/concept/lasagna/.docs/hints.md b/exercises/concept/lasagna/.docs/hints.md index ec75b57e..5a17a15d 100644 --- a/exercises/concept/lasagna/.docs/hints.md +++ b/exercises/concept/lasagna/.docs/hints.md @@ -17,22 +17,21 @@ - The first command-line argument is the [positional parameter][positional] `$1`. - Use a default value to handle a missing argument: `${1:-0}`. -- [Command substitution][cmd-subst] captures the output of a command: `result=$(command args)`. -- `expr 7 - 2` outputs `5`. - Give it the variables as arguments, in quotes. +- [Arithmetic expansion][arithmetic] expands to the result of a calculation: `result=$(( 7 - 2 ))`. +- Inside `$(( ))`, you can use variable names without the `$`. ## 3. Calculate the preparation time in minutes - The second command-line argument is `$2`. - Remember to provide a default for a missing argument. -- `expr` needs the multiplication operator to be quoted so that bash does not treat it as a filename pattern: `expr "$a" '*' "$b"`. +- Use `*` to multiply: `$(( a * b ))`. - Store the minutes per layer in a variable, so the number 2 has a name. ## 4. Calculate the total working time in minutes -- `expr "$a" + "$b"` adds two numbers. +- `$(( a + b ))` adds two numbers. - You can reuse the variables you have already assigned. [echo]: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins [positional]: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters -[cmd-subst]: https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution +[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Arithmetic-Expansion diff --git a/exercises/concept/lasagna/.docs/instructions.md b/exercises/concept/lasagna/.docs/instructions.md index f8e19314..fb6a9e0b 100644 --- a/exercises/concept/lasagna/.docs/instructions.md +++ b/exercises/concept/lasagna/.docs/instructions.md @@ -19,8 +19,8 @@ Run the script with: bash lasagna.sh 18 3 ``` -Bash does not yet have arithmetic in this syllabus, so you can use the external `expr` command to do the math, and command substitution to capture its result. -For example, `expr 7 - 2` outputs `5`. +Use arithmetic expansion to do the math. +For example, `$(( 7 - 2 ))` expands to `5`. ## 1. Define the expected oven time in minutes diff --git a/exercises/concept/lasagna/.docs/introduction.md b/exercises/concept/lasagna/.docs/introduction.md index 64f99ab7..49fb0c30 100644 --- a/exercises/concept/lasagna/.docs/introduction.md +++ b/exercises/concept/lasagna/.docs/introduction.md @@ -47,6 +47,8 @@ For example, to print the string `10x10` echo "${x}x$x" ``` +Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. + ### Positional Parameters As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. @@ -88,30 +90,57 @@ echo "Running on $kernel" # => Running on Linux ``` -## Arithmetic with `expr` +### Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` -Bash has its own way to do arithmetic, which you will learn about later. -For now, you can use the external `expr` command. -It takes the numbers and the operator as separate arguments, so each must be a separate word, and it prints the result: +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: ```bash -expr 7 - 2 -# => 5 +x=$(( 3 + 4 )) ``` -Combine it with command substitution to store the result in a variable. -Remember that quoting your variable expansions keeps each value as a single argument: +Inside the parentheses, you can use a variable's name without the `$`: ```bash -total=$(expr "$a" + "$b") +height=10 +width=20 +area=$(( height * width )) ``` -Some operators have a special meaning to Bash. -For example, an unquoted `*` is a filename pattern, which Bash replaces with the names of the files in the current directory. -Quote such an operator so that `expr` receives it as an argument: +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. ```bash -product=$(expr "$a" '*' "$b") +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +### Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) ``` +[google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments diff --git a/exercises/concept/lasagna/.docs/introduction.md.tpl b/exercises/concept/lasagna/.docs/introduction.md.tpl index 40da1aa6..fd7059b7 100644 --- a/exercises/concept/lasagna/.docs/introduction.md.tpl +++ b/exercises/concept/lasagna/.docs/introduction.md.tpl @@ -1,29 +1,3 @@ # Introduction %{concept:variables} - -## Arithmetic with `expr` - -Bash has its own way to do arithmetic, which you will learn about later. -For now, you can use the external `expr` command. -It takes the numbers and the operator as separate arguments, so each must be a separate word, and it prints the result: - -```bash -expr 7 - 2 -# => 5 -``` - -Combine it with command substitution to store the result in a variable. -Remember that quoting your variable expansions keeps each value as a single argument: - -```bash -total=$(expr "$a" + "$b") -``` - -Some operators have a special meaning to bash. -For example, an unquoted `*` is a filename pattern, which bash replaces with the names of the files in the current directory. -Quote such an operator so that `expr` receives it as an argument: - -```bash -product=$(expr "$a" '*' "$b") -``` diff --git a/exercises/concept/lasagna/.meta/design.md b/exercises/concept/lasagna/.meta/design.md index dd8eecf2..e78fd7bc 100644 --- a/exercises/concept/lasagna/.meta/design.md +++ b/exercises/concept/lasagna/.meta/design.md @@ -12,10 +12,11 @@ The goal of this exercise is to introduce variables in bash scripts. - Read command-line arguments through positional parameters. - Provide a default value with `${name:-default}`. - Capture the output of a command in a variable with command substitution. +- Do integer arithmetic with arithmetic expansion. ## Out of scope -- Arithmetic expansion; `expr` is used instead. +- Other arithmetic contexts, such as the `(( ))` conditional. - Arrays. - Functions and `local` variables. - Exported variables and the environment. diff --git a/exercises/concept/lasagna/.meta/exemplar.sh b/exercises/concept/lasagna/.meta/exemplar.sh index 5e24db25..ac4958ad 100644 --- a/exercises/concept/lasagna/.meta/exemplar.sh +++ b/exercises/concept/lasagna/.meta/exemplar.sh @@ -1,9 +1,5 @@ #!/usr/bin/env bash -# `expr` is an external command that does simple arithmetic. -# Bash has a builtin way to do this, which a later concept will cover. -# shellcheck disable=SC2003 - expected_minutes_in_oven=40 minutes_per_layer=2 @@ -14,13 +10,13 @@ number_of_layers=${2:-1} echo "Expected minutes in oven: ${expected_minutes_in_oven}" # Task 2 -remaining_minutes_in_oven=$(expr "$expected_minutes_in_oven" - "$actual_minutes_in_oven") +remaining_minutes_in_oven=$(( expected_minutes_in_oven - actual_minutes_in_oven )) echo "Remaining minutes in oven: ${remaining_minutes_in_oven}" # Task 3 -preparation_time=$(expr "$number_of_layers" '*' "$minutes_per_layer") +preparation_time=$(( number_of_layers * minutes_per_layer )) echo "Preparation time in minutes: ${preparation_time}" # Task 4 -total_time=$(expr "$preparation_time" + "$actual_minutes_in_oven") +total_time=$(( preparation_time + actual_minutes_in_oven )) echo "Total time in minutes: ${total_time}" From cc3ac3fe6cbfca32e0a4b76d40ec4a1fb776ed74 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sat, 28 Nov 2026 10:47:45 -0500 Subject: [PATCH 4/7] Add road map to the exercises/concept directory --- exercises/concept/road-map.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 exercises/concept/road-map.md diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md new file mode 100644 index 00000000..ad718fdb --- /dev/null +++ b/exercises/concept/road-map.md @@ -0,0 +1,18 @@ +# Road map to implement bash concept exercises + +Ref: [Syllabus](https://exercism.org/docs/tracks/bash/syllabus) + +| Concept | Prereq | Exercise | branch or PR | branched from | +| ------- | ------ | -------- | ------------ | ------------- | +| [commands-and-arguments](https://github.com/exercism/bash/tree/main/concepts/commands-and-arguments) | - | [shopping](https://github.com/exercism/bash/tree/main/exercises/concept/shopping) | [980](https://github.com/exercism/bash/pull/980) | | +| [variables](https://github.com/exercism/bash/tree/main/concepts/variables) | cmds-args | [lasagna](https://github.com/glennj/exercism-bash/tree/concept-exercise-lasagna) | [985](https://github.com/exercism/bash/pull/985) | main | +| [quoting](https://github.com/exercism/bash/tree/main/concepts/quoting) | variables | [messy-downloads](https://github.com/glennj/exercism-bash/tree/concept-expercise-quoting) | | lasagna | +| [conditionals](https://github.com/exercism/bash/tree/main/concepts/conditionals) | quoting | cars-assemble | | | +| [arithmetic](https://github.com/exercism/bash/tree/main/concepts/arithmetic) | quoting | cars-assemble | | | +| [looping](https://github.com/exercism/bash/tree/main/concepts/looping) | conditionals | | | | +| [arrays](https://github.com/exercism/bash/tree/main/concepts/arrays) | quoting | | | | +| [more-arrays](https://github.com/exercism/bash/tree/main/concepts/more-arrays) | arrays | | | | +| [pipelines](https://github.com/exercism/bash/tree/main/concepts/pipelines) | quoting | | | | +| [functions](https://github.com/exercism/bash/tree/main/concepts/functions) | pipelines | | | | +| [redirection](https://github.com/exercism/bash/tree/main/concepts/redirection) | pipelines | | | | +| [heredocs](https://github.com/exercism/bash/tree/main/concepts/heredocs) | redirection | | | | From 6c3d996a58a37a063319c6fce252216d270f4ccf Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sat, 28 Nov 2026 12:20:21 -0500 Subject: [PATCH 5/7] for default values, note there are other expansions --- concepts/variables/introduction.md | 4 ++++ exercises/concept/lasagna/.docs/introduction.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/concepts/variables/introduction.md b/concepts/variables/introduction.md index 84979bf5..64969094 100644 --- a/concepts/variables/introduction.md +++ b/concepts/variables/introduction.md @@ -71,6 +71,9 @@ echo "Hello, $name" # => Hello, world (when the script is given no arguments) ``` +There are several other forms of parameter expansion that perform various manipulations. +Read about them in [Shell Parameter Expansion][param-exp] in the bash manual. + ## Command Substitution A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. @@ -142,3 +145,4 @@ eggs=$(( cartons * eggs_per_carton )) [google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments +[param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion diff --git a/exercises/concept/lasagna/.docs/introduction.md b/exercises/concept/lasagna/.docs/introduction.md index 49fb0c30..693e3627 100644 --- a/exercises/concept/lasagna/.docs/introduction.md +++ b/exercises/concept/lasagna/.docs/introduction.md @@ -73,6 +73,9 @@ echo "Hello, $name" # => Hello, world (when the script is given no arguments) ``` +There are several other forms of parameter expansion that perform various manipulations. +Read about them in [Shell Parameter Expansion][param-exp] in the bash manual. + ### Command Substitution A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. @@ -144,3 +147,4 @@ eggs=$(( cartons * eggs_per_carton )) [google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments +[param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion From 4d9cd1274472e3eb822ac8e051221c7ec94585d0 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sat, 28 Nov 2026 12:20:33 -0500 Subject: [PATCH 6/7] road map --- exercises/concept/road-map.md | 49 ++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md index ad718fdb..5f5f74c5 100644 --- a/exercises/concept/road-map.md +++ b/exercises/concept/road-map.md @@ -1,18 +1,37 @@ # Road map to implement bash concept exercises -Ref: [Syllabus](https://exercism.org/docs/tracks/bash/syllabus) +Ref: [Syllabus][syllabus] -| Concept | Prereq | Exercise | branch or PR | branched from | -| ------- | ------ | -------- | ------------ | ------------- | -| [commands-and-arguments](https://github.com/exercism/bash/tree/main/concepts/commands-and-arguments) | - | [shopping](https://github.com/exercism/bash/tree/main/exercises/concept/shopping) | [980](https://github.com/exercism/bash/pull/980) | | -| [variables](https://github.com/exercism/bash/tree/main/concepts/variables) | cmds-args | [lasagna](https://github.com/glennj/exercism-bash/tree/concept-exercise-lasagna) | [985](https://github.com/exercism/bash/pull/985) | main | -| [quoting](https://github.com/exercism/bash/tree/main/concepts/quoting) | variables | [messy-downloads](https://github.com/glennj/exercism-bash/tree/concept-expercise-quoting) | | lasagna | -| [conditionals](https://github.com/exercism/bash/tree/main/concepts/conditionals) | quoting | cars-assemble | | | -| [arithmetic](https://github.com/exercism/bash/tree/main/concepts/arithmetic) | quoting | cars-assemble | | | -| [looping](https://github.com/exercism/bash/tree/main/concepts/looping) | conditionals | | | | -| [arrays](https://github.com/exercism/bash/tree/main/concepts/arrays) | quoting | | | | -| [more-arrays](https://github.com/exercism/bash/tree/main/concepts/more-arrays) | arrays | | | | -| [pipelines](https://github.com/exercism/bash/tree/main/concepts/pipelines) | quoting | | | | -| [functions](https://github.com/exercism/bash/tree/main/concepts/functions) | pipelines | | | | -| [redirection](https://github.com/exercism/bash/tree/main/concepts/redirection) | pipelines | | | | -| [heredocs](https://github.com/exercism/bash/tree/main/concepts/heredocs) | redirection | | | | +| Concept | Exercise | branch or PR | Prereq | +| ------- | -------- | ------------ | ------ | +| [commands-and-arguments][commands-and-arguments] | shopping | [980][980] | - | +| [variables][variables] | [lasagna][lasagna] | [985][985] | cmds-args | +| [quoting][quoting] | messy-downloads (OC) | [branch][concept-expercise-quoting] | variables | +| [conditionals][conditionals] | [vehicle-purchase][vehicle-purchase] | | quoting | +| [arithmetic][arithmetic] | [vehicle-purchase][vehicle-purchase] | | quoting | +| [looping][looping] | | | conditionals | +| [arrays][arrays] | | | quoting | +| [more-arrays][more-arrays] | | | arrays | +| [pipelines][pipelines] | | | quoting | +| [functions][functions] | | | pipelines | +| [redirection][redirection] | | | pipelines | +| [heredocs][heredocs] | | | redirection | + +[syllabus]: https://exercism.org/docs/tracks/bash/syllabus +[commands-and-arguments]: https://github.com/exercism/bash/tree/main/concepts/commands-and-arguments +[980]: https://github.com/exercism/bash/pull/980 +[variables]: https://exercism.org/docs/building/tracks/stories/basics-lasagna +[lasagna]: https://github.com/glennj/exercism-bash/tree/concept-exercise-lasagna +[985]: https://github.com/exercism/bash/pull/985 +[quoting]: https://github.com/exercism/bash/tree/main/concepts/quoting +[concept-expercise-quoting]: https://github.com/glennj/exercism-bash/tree/concept-expercise-quoting +[conditionals]: https://github.com/exercism/bash/tree/main/concepts/conditionals +[vehicle-purchase]: https://exercism.org/docs/building/tracks/stories/conditionals-vehicle-purchase +[arithmetic]: https://github.com/exercism/bash/tree/main/concepts/arithmetic +[looping]: https://github.com/exercism/bash/tree/main/concepts/looping +[arrays]: https://github.com/exercism/bash/tree/main/concepts/arrays +[more-arrays]: https://github.com/exercism/bash/tree/main/concepts/more-arrays +[pipelines]: https://github.com/exercism/bash/tree/main/concepts/pipelines +[functions]: https://github.com/exercism/bash/tree/main/concepts/functions +[redirection]: https://github.com/exercism/bash/tree/main/concepts/redirection +[heredocs]: https://github.com/exercism/bash/tree/main/concepts/heredocs From ecc7ed382d92152516c7ef578a3c652a9e32975a Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sun, 29 Nov 2026 07:14:40 -0500 Subject: [PATCH 7/7] restore concept "about" content into the introduction(s) --- concepts/variables/introduction.md | 118 ++++++++++++++---- .../concept/lasagna/.docs/introduction.md | 117 +++++++++++++---- 2 files changed, 185 insertions(+), 50 deletions(-) diff --git a/concepts/variables/introduction.md b/concepts/variables/introduction.md index 64969094..cbee49f8 100644 --- a/concepts/variables/introduction.md +++ b/concepts/variables/introduction.md @@ -1,8 +1,12 @@ # Introduction to Variables +## Variables + _Variables_ are a place to hold data. -You assign a variable like this +Bash has two kinds of data: strings and arrays. +We'll talk about arrays later. +You assign a variable like this ```bash name="value" ``` @@ -19,6 +23,19 @@ x = 10 bash is going to call the **command** `x` with the **two arguments** `=` and `10`! ~~~~ +Variables can also be called _parameters_. +The two terms will be used interchangably in this document. + +Some important parameters used by or set by bash include: + +* `PATH` -- a colon-separated list of directories used to find external commands. +* `IFS` -- the "internal field separator". + We'll see how it's used below. +* `PWD` -- your current working directory. + It will be the same value as the output of the `pwd` command. +* `RANDOM` -- a pseudo-random integer between 0 and 32767. +* `BASH_VERSION` -- the version string of the running instance of bash. + ## Variable Names A variable name consists of _uppercase letters, lowercase letters, numbers and underscore_. @@ -26,23 +43,30 @@ It cannot start with a number. ~~~~exercism/caution It is best practice to **avoid using ALLCAPS variable names**. -The shell uses this convention for its own variables, and you don't want to accidentally overwrite one that has a special meaning. +The shell uses this convention for its parameters, and you don't want to accidentally overwrite shell parameters that have special meaning. +For example: [1][1], [2][2], [3][3] + +[1]: https://stackoverflow.com/q/27555060/7552 +[2]: https://stackoverflow.com/q/28310594/7552 +[3]: https://unix.stackexchange.com/q/114596/4667 ~~~~ ## Parameter Expansion -You get the value of a variable with the `$varname` syntax. +You get the value of a parameter with the `$varname` syntax. ```bash x=10 echo "The value of x is $x" ``` -To prevent the variable name from being confused with surrounding text, enclose the variable name in braces. -For example, to print the string `10x10` +To prevent the variable name from being confused with surrounding text, you can enclose the variable name in braces. +For example to print the string `10x10` ```bash echo "${x}x$x" +# or +echo "${x}x${x}" ``` Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. @@ -51,44 +75,53 @@ Some [style guides][google-style-guide] recommend using braces in most cases for As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. Bash scripts are no exception. -The arguments to a script are called _positional parameters_. -You can retrieve them with `$1` (the first argument), `$2` (the second argument), and so on. +The arguments to the current instance of bash are called _positional parameters_. +They can be retrieved with these special parameters: -```bash -# run as: bash greet.sh Alice Bob -echo "Hello, $1 and $2" -# => Hello, Alice and Bob -``` +* `$1` -- the first positional parameter +* `$2` ... `$9` -- subsequent parameters +* `${10}` ... -- double digits require braces. +* `$0` -- the name of the current script. + +Arguments to a shell function are also positional parameters, handled just like this. +We'll see more about functions in a later lesson. + +### Special Positional Parameters + +There are some _special parameters_ that help you work with the positional parameters. -## Default Values +* `$#` expands to the _number_ of positional parameters. +* `"$@"` expands to the list of all of the positional parameters, each as a separate word. +* `"$*"` expands to a single string of all the positional parameters joined together by a character. + * The join character is _the first character_ of the `$IFS` variable, which is a space by default. -Use `${varname:-default}` to provide a default value when the variable is empty or unset. -This is useful for arguments that may be missing. +The `"$@"` is the safest way to pass positional parameters to another command while keeping them safely quoted. +It is also what you will use to loop over the positional parameters: ```bash -name=${1:-world} -echo "Hello, $name" -# => Hello, world (when the script is given no arguments) +for arg in "$@"; do + do_something_with "$arg" +done ``` -There are several other forms of parameter expansion that perform various manipulations. -Read about them in [Shell Parameter Expansion][param-exp] in the bash manual. +In practice, `"$@"` is used more often than `"$*"`. ## Command Substitution A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. -To do this, use _command substitution_. +To do this, you will use _command substitution_. ```bash var=$(command) ``` -For example: +For example, to upper-case a string, you can do this: ```bash -kernel=$(uname -s) -echo "Running on $kernel" -# => Running on Linux +text="Hello world!" +uppercase=$(echo "$text" | tr '[:lower:]' '[:upper:]') +echo "$uppercase" +# => HELLO WORLD! ``` ## Arithmetic Expansion @@ -143,6 +176,41 @@ eggs_per_carton=12 eggs=$(( cartons * eggs_per_carton )) ``` +## More on Parameter Expansion + +Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. + +* Uppercasing text. + In the previous section I showed how to use `tr` to upper case some text. + To do it in bash: + + ```bash + echo "${text^^}" + ``` + + Similarly, `${text,,}` lowercases the value. + +* Provide a default value if the variable is empty. + + ```bash + default="nothing here" + result="" + echo "${result:-$default}" + # => nothing here + ``` + +* Search and replace. + + ```bash + text="Hello world!" + echo "${text//[aeiou]/X}" + # => HXllX wXrld!" + ``` + +There are many other interesting parameter expansions: extract a substring, get the string length, _assign_ a default value, remove text from the start or end of the value, and more. +Read about them [in the manual][param-exp]. + + [google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments [param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion diff --git a/exercises/concept/lasagna/.docs/introduction.md b/exercises/concept/lasagna/.docs/introduction.md index 693e3627..784ef8a2 100644 --- a/exercises/concept/lasagna/.docs/introduction.md +++ b/exercises/concept/lasagna/.docs/introduction.md @@ -2,9 +2,13 @@ ## Variables +### Variables + _Variables_ are a place to hold data. -You assign a variable like this +Bash has two kinds of data: strings and arrays. +We'll talk about arrays later. +You assign a variable like this ```bash name="value" ``` @@ -21,6 +25,19 @@ x = 10 bash is going to call the **command** `x` with the **two arguments** `=` and `10`! ~~~~ +Variables can also be called _parameters_. +The two terms will be used interchangably in this document. + +Some important parameters used by or set by bash include: + +* `PATH` -- a colon-separated list of directories used to find external commands. +* `IFS` -- the "internal field separator". + We'll see how it's used below. +* `PWD` -- your current working directory. + It will be the same value as the output of the `pwd` command. +* `RANDOM` -- a pseudo-random integer between 0 and 32767. +* `BASH_VERSION` -- the version string of the running instance of bash. + ### Variable Names A variable name consists of _uppercase letters, lowercase letters, numbers and underscore_. @@ -28,23 +45,30 @@ It cannot start with a number. ~~~~exercism/caution It is best practice to **avoid using ALLCAPS variable names**. -The shell uses this convention for its own variables, and you don't want to accidentally overwrite one that has a special meaning. +The shell uses this convention for its parameters, and you don't want to accidentally overwrite shell parameters that have special meaning. +For example: [1][1], [2][2], [3][3] + +[1]: https://stackoverflow.com/q/27555060/7552 +[2]: https://stackoverflow.com/q/28310594/7552 +[3]: https://unix.stackexchange.com/q/114596/4667 ~~~~ ### Parameter Expansion -You get the value of a variable with the `$varname` syntax. +You get the value of a parameter with the `$varname` syntax. ```bash x=10 echo "The value of x is $x" ``` -To prevent the variable name from being confused with surrounding text, enclose the variable name in braces. -For example, to print the string `10x10` +To prevent the variable name from being confused with surrounding text, you can enclose the variable name in braces. +For example to print the string `10x10` ```bash echo "${x}x$x" +# or +echo "${x}x${x}" ``` Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. @@ -53,44 +77,53 @@ Some [style guides][google-style-guide] recommend using braces in most cases for As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. Bash scripts are no exception. -The arguments to a script are called _positional parameters_. -You can retrieve them with `$1` (the first argument), `$2` (the second argument), and so on. +The arguments to the current instance of bash are called _positional parameters_. +They can be retrieved with these special parameters: -```bash -# run as: bash greet.sh Alice Bob -echo "Hello, $1 and $2" -# => Hello, Alice and Bob -``` +* `$1` -- the first positional parameter +* `$2` ... `$9` -- subsequent parameters +* `${10}` ... -- double digits require braces. +* `$0` -- the name of the current script. + +Arguments to a shell function are also positional parameters, handled just like this. +We'll see more about functions in a later lesson. + +#### Special Positional Parameters -### Default Values +There are some _special parameters_ that help you work with the positional parameters. -Use `${varname:-default}` to provide a default value when the variable is empty or unset. -This is useful for arguments that may be missing. +* `$#` expands to the _number_ of positional parameters. +* `"$@"` expands to the list of all of the positional parameters, each as a separate word. +* `"$*"` expands to a single string of all the positional parameters joined together by a character. + * The join character is _the first character_ of the `$IFS` variable, which is a space by default. + +The `"$@"` is the safest way to pass positional parameters to another command while keeping them safely quoted. +It is also what you will use to loop over the positional parameters: ```bash -name=${1:-world} -echo "Hello, $name" -# => Hello, world (when the script is given no arguments) +for arg in "$@"; do + do_something_with "$arg" +done ``` -There are several other forms of parameter expansion that perform various manipulations. -Read about them in [Shell Parameter Expansion][param-exp] in the bash manual. +In practice, `"$@"` is used more often than `"$*"`. ### Command Substitution A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. -To do this, use _command substitution_. +To do this, you will use _command substitution_. ```bash var=$(command) ``` -For example: +For example, to upper-case a string, you can do this: ```bash -kernel=$(uname -s) -echo "Running on $kernel" -# => Running on Linux +text="Hello world!" +uppercase=$(echo "$text" | tr '[:lower:]' '[:upper:]') +echo "$uppercase" +# => HELLO WORLD! ``` ### Arithmetic Expansion @@ -145,6 +178,40 @@ eggs_per_carton=12 eggs=$(( cartons * eggs_per_carton )) ``` +### More on Parameter Expansion + +Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. + +* Uppercasing text. + In the previous section I showed how to use `tr` to upper case some text. + To do it in bash: + + ```bash + echo "${text^^}" + ``` + + Similarly, `${text,,}` lowercases the value. + +* Provide a default value if the variable is empty. + + ```bash + default="nothing here" + result="" + echo "${result:-$default}" + # => nothing here + ``` + +* Search and replace. + + ```bash + text="Hello world!" + echo "${text//[aeiou]/X}" + # => HXllX wXrld!" + ``` + +There are many other interesting parameter expansions: extract a substring, get the string length, _assign_ a default value, remove text from the start or end of the value, and more. +Read about them [in the manual][param-exp]. + [google-style-guide]: https://google.github.io/styleguide/shellguide.html [cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments [param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion