Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions POLICIES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
121 changes: 23 additions & 98 deletions concepts/variables/introduction.md
Original file line number Diff line number Diff line change
@@ -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"
```
Expand All @@ -23,142 +19,71 @@ 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_.
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
16 changes: 14 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down Expand Up @@ -674,10 +686,10 @@
"practices": [],
"prerequisites": [],
"difficulty": 4,
"status": "wip",
"topics": [
"dates"
],
"status": "wip"
]
},
{
"slug": "binary-search",
Expand Down
38 changes: 38 additions & 0 deletions exercises/concept/lasagna/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -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
73 changes: 73 additions & 0 deletions exercises/concept/lasagna/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -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
```
Loading
Loading