Skip to content
Merged
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
2 changes: 1 addition & 1 deletion concepts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ erDiagram
"Commands and Arguments" ||--|| Variables : ""
Variables ||--|| "The Importance of Quoting" : ""
"The Importance of Quoting" ||--|| Conditionals : ""
"The Importance of Quoting" ||--|| Arrays : ""
Looping ||--|| Arrays : ""
"The Importance of Quoting" ||--|| "Pipelines and Command Lists" : ""
Conditionals ||--|| Arithmetic : ""
Conditionals ||--|| Looping : ""
Expand Down
12 changes: 12 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@
"quoting"
],
"status": "wip"
},
{
"slug": "bird-watcher",
"name": "Bird Watcher",
"uuid": "2493723d-786c-4361-a92f-f30837caea95",
"concepts": [
"looping"
],
"prerequisites": [
"conditionals"
],
"status": "wip"
}
],
"practice": [
Expand Down
4 changes: 2 additions & 2 deletions docs/SYLLABUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ While the learning exercises are still incomplete, most of the concept documenta
* [Conditionals](https://exercism.org/tracks/bash/concepts/conditionals)
* [Arithmetic](https://exercism.org/tracks/bash/concepts/arithmetic)
* [Looping](https://exercism.org/tracks/bash/concepts/looping)
* [Arrays](https://exercism.org/tracks/bash/concepts/arrays)
* [More About Arrays](https://exercism.org/tracks/bash/concepts/more-arrays)
* [Arrays](https://exercism.org/tracks/bash/concepts/arrays)
* [More About Arrays](https://exercism.org/tracks/bash/concepts/more-arrays)
* [Pipelines and Command Lists](https://exercism.org/tracks/bash/concepts/pipelines)
* [Functions](https://exercism.org/tracks/bash/concepts/functions)
* [Redirection](https://exercism.org/tracks/bash/concepts/redirection)
Expand Down
42 changes: 42 additions & 0 deletions exercises/concept/bird-watcher/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Hints

## General

- Read about [looping constructs][looping-constructs] in the bash manual, or the track's looping concept page.
- Add to a number with [arithmetic expansion][arithmetic]: `total=$(( total + 1 ))`.
- Set your totals and counters to their starting values before a loop begins.
- Quote your parameter expansions: `"$@"`.

## 1. Count all the birds

- Use a [`for` loop][looping-constructs] to visit each of the `"$@"` arguments.
- Add each count to a total, then print the total after the loop.

## 2. Find the first quiet day

- Keep track of the day number while you loop over the counts.
- Compare numbers for equality with `==` inside `(( ... ))`.
- Use [`break`][builtins] to leave the loop early.
- Before the loop, store the answer to print if there is no quiet day.

## 3. Draw a bar of a chart

- An [arithmetic `for` loop][looping-constructs] can repeat commands a given number of times.
- Build up the stars in a variable: `bar="${bar}*"`.
- Print the variable after the loop, inside double quotes.

## 4. Predict when you will reach your goal

- You don't know in advance how many days you need, so use a [`while` loop][looping-constructs].
- The condition can be an arithmetic comparison: `(( ... ))`.
- Each time around the loop, update the total, the number of birds, and the number of days.

## 5. Summarize your log file

- Read the file line by line with `while IFS= read -r line`, and redirect the file into the loop after `done`.
- Add `|| [[ -n $line ]]` to the condition to handle a last line without a newline.
- Use [`continue`][builtins] to skip a rainy day.

[looping-constructs]: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
[builtins]: https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins
[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Arithmetic-Expansion
91 changes: 91 additions & 0 deletions exercises/concept/bird-watcher/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Instructions

You are an avid bird watcher.
Every day you count the birds that visit your garden, and now you want a script to help you work with those counts.

You have five tasks, and they all belong to the same script.
The first argument names the task to perform, and the remaining arguments are the data for that task.
The script you are given already runs the right part of the code for each task, so you only need to fill in each part.
Do not print anything other than the requested output.

## 1. Count all the birds

The arguments are the number of birds you counted on each day.
There can be any number of days, including none at all.

Print the total number of birds.

```text
$ bash bird_watcher.sh total 2 5 0 7 4
18
```

## 2. Find the first quiet day

The arguments are the daily counts.
A quiet day is a day when you saw no birds at all.

Print the number of the first quiet day, where the first day is day 1.
If there was no quiet day, print `none`.
Stop looking as soon as you find a quiet day.

```text
$ bash bird_watcher.sh quiet-day 2 5 0 7 0
3
```

## 3. Draw a bar of a chart

The argument is the number of birds you counted on one day.

Print one line containing one `*` for each bird.
If there were no birds, print an empty line.

```text
$ bash bird_watcher.sh chart 3
***
```

## 4. Predict when you will reach your goal

Spring is coming, and you expect to see one more bird each day than the day before.
The first argument is the total number of birds you want to see.
The second argument is the number of birds you expect to see on the first day.

Print the number of days needed for the total to reach or pass the goal.

For example, with 2 birds on the first day, you expect to see 2, 3, 4 and then 5 birds.
The totals after each day are 2, 5, 9 and 14, so a goal of 10 birds takes 4 days.

```text
$ bash bird_watcher.sh goal 10 2
4
```

## 5. Summarize your log file

You have also been keeping a log file, with one line for each day.
A line contains either the number of birds you saw, or the word `rain` for a day when you stayed indoors.
The last line of the file might not end with a newline.

The argument is the name of the file.
Print the total number of birds, and the number of days that you were watching.
Rainy days are not days that you were watching.

If the file `birds.txt` contains these lines:

```text
2
5
rain
0
7
3
```

then the output is:

```text
$ bash bird_watcher.sh log birds.txt
17 birds in 5 days
```
183 changes: 183 additions & 0 deletions exercises/concept/bird-watcher/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
# Introduction

## Looping

Bash has two forms of looping:

* Repeat some commands _for each item in a list of items_,
* Repeat some commands _while some condition is true (or false)_.

### For Loops

To iterate over a list of items, we use the `for` loop.

```bash
for varname in words; do COMMANDS; done
```

`words` is expanded using word splitting and filename expansion (that we learned about in the [Quoting concept][quoting]).
Each word is assigned to the `varname` in turn, and the COMMANDS are executed.

Here are some examples that show when the for loop can be useful

* Perform some commands on a group of files.

```bash
# source all the bash library files in the current directory
for file in ./*.bash; do
source "$file"
done
```

* Perform some command on each of the parameters to a script or function.

```bash
for arg in "$@"; do
echo "argument: ${arg}"
done
```

* Perform some command for each whitespace-separated word in the output of a command.

```bash
for i in $(seq 10); do
echo "${i} squared is $((i * i))"
done
```

We'll see some warnings about this style later on.

#### Arithmetic For Loop

Bash does have an arithmetic loop.
This will look somewhat familiar to other programming languages.

```bash
for ((INITIALIZATION; CONDITION; INCREMENT)); do COMMANDS; done
```

The double-parentheses in bash represents an arithmetic context (we'll see more about bash arithmetic in a later concept).
The above example using `seq` can be written like this

```bash
for ((i = 1; i <= 10; i++)); do
echo "${i} squared is $((i * i))"
done
```

#### When Not To Use For

[Don't read lines with `for`][bashfaq1].

This is an anti-pattern you'll often see: iterating over the output of `cat`.

```bash
for line in $(cat some.file); do
do_something_with "$line"
done
```

This is wrong on 2 counts.

1. The command substitution is unquoted, so it is subject to word splitting.
Word splitting, by default, splits on _whitespace_ not just newlines.
This for loop is iterating over the **words** in the file, not the lines.
2. The command substitution is unquoted, so it is subject to filename expansion.
Every word in the file will be matched as a glob pattern.

As we learned in the [Quoting concept][quoting], word splitting can be controlled with the `IFS` variable, and filename expansion can be turned off.
But this tends to be a fragile solution.
`for` is the wrong method to iterate over the lines of a file.
The idiomatic way to read a file is with a `while` loop.

### While Loops

Use `while` to repeat a sequence of commands _while_ some condition is true.

```bash
while CONDITION_COMMANDS; do COMMANDS; done
```

As with `if` (as we learned in the [Conditionals concept][conditionals], there is no special syntax for CONDITION_COMMANDS.
The exit status of the command list will determine "true" or "false".

### Controlling Loops

The `break` command jumps out of the loop.
Control resumes with the command following the loop's `done` terminator.

The `continue` command jumps to the next iteration of the loop.

### Reading the Lines of a File

As mentioned, a while loop is the idiomatic way to read a file.

```bash
while IFS= read -r line; do
do_something_with "$line"
done < some.file
```

* The content of the file is provided as input to the loop with the `<` redirection.
* The `read` command returns "true" if it can read a full line from its input.
When the input is consumed, or if the last line ends without a trailing newline, then read returns "false".
* The _truly_ idiomatic way to read the lines of a file, even if the last line does not end with a newline, is

```bash
while IFS= read -r line || [[ -n "$line" ]]; do ...
```

* The `-r` option tells `read` to not substitute backslash sequences: a backslash is just a plain character.
* `IFS=` assigns the empty string to IFS only for the duration of the read command.
This temporarily turns off word splitting so that any leading or trailing whitespace in the incoming line of text is preserved.

### Until

The `until` construct repeats a sequence of commands while some condition is **false**.
The loop repeats _until_ the condition becomes true.

```bash
until CONDITION_COMMANDS; do COMMANDS; done
```

It is rare to use `until`.
It is more common to use a "while not" loop.

```bash
while ! CONDITION_COMANDS; do ...
```

### Infinite Loops

Sometimes you want to loop forever.
Here are two ways to do it.

1. a while loop with a condition that always has a success exit status

```bash
while true; do ...
```

2. an arithmetic for loop with empty expressions

```bash
for ((;;)); do ...
```

### Do-While

There is no explicit do-while construct, but you can achieve the same effect:

```bash
while true; do
COMMANDS

if END_CONDITION; then
break
fi
done
```

[bashfaq1]: https://mywiki.wooledge.org/DontReadLinesWithFor
[quoting]: https://exercism.org/tracks/bash/concepts/quoting
[conditionals]: https://exercism.org/tracks/bash/concepts/conditionals
3 changes: 3 additions & 0 deletions exercises/concept/bird-watcher/.docs/introduction.md.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Introduction

%{concept:looping}
23 changes: 23 additions & 0 deletions exercises/concept/bird-watcher/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"authors": [
"glennj"
],
"files": {
"solution": [
"bird_watcher.sh"
],
"test": [
"bird_watcher.bats"
],
"exemplar": [
".meta/exemplar.sh"
],
"invalidator": [
"bats-extra.bash"
]
},
"forked_from": [
"javascript/bird-watcher"
],
"blurb": "Learn about looping while counting the birds that visit your garden."
}
Loading
Loading