Lecture 13: Loops
Overview
Burton Ma explains Bash's `while`, `until`, for-each, and C-style counting loops, emphasizing that loop conditions use command exit statuses and that quoting controls how values are split. Examples include countdowns, the Collatz conjecture, safe processing of script arguments and files, and an introduction to Bash functions and their positional parameters.
Key takeaways
- Bash loop conditions use command exit statuses: status 0 is treated as true, so `while false` does not run and `until false` runs indefinitely.
- Use `"$@"` to iterate over command-line arguments without splitting arguments that contain spaces; use `shift` with `$#` when processing parameters sequentially.
- A Bash glob with no matches can remain as a literal pattern, so a loop over `*.pdf` may run once with the text `*.pdf` rather than reporting an error.
- Use `while IFS= read -r line` with input redirection to process a file line by line while preserving backslashes; set `IFS` to a comma when parsing comma-separated fields.
- Use `for ((i=10; i>=0; i--))` for a numeric countdown, reserving for-each loops for sequences of strings or expanded values.
- Bash functions receive arguments through positional parameters, but their `$1` and `$#` values are separate from the calling script's positional parameters.
Chapters
- Bash supports `while` loops, `until` loops, and the `break` and `continue` keywords; it does not have Java's `do-while` loop.
- A condition is evaluated through a command's exit status: status 0 means success, while a nonzero status means failure.
- `until false` runs indefinitely because the `false` command always returns a nonzero status.
- Double square brackets and double parentheses can express loop conditions, with double parentheses used for arithmetic comparisons.
- A Bash `until` loop can count from 10 to 0 by decrementing a variable until it passes the stopping condition.
- A `while` loop can produce the same countdown by continuing while the count remains greater than -1.
- The Collatz conjecture repeatedly halves a positive even integer or transforms an odd integer with `3n + 1`, with the conjecture that the sequence eventually reaches 1.
- The odd step can increase a value while the even step decreases it, and Burton Ma notes that computations had tested starting values as high as 2^68 by 2020.
- The `collatz` script checks that an input argument exists, sends error messages to standard error, and exits with a nonzero status on invalid input.
- A regular expression such as `^[+-]?[0-9]+$` checks that the argument is a signed integer; a further arithmetic check rejects values below 1.
- The script uses a `while` loop until the current value equals 1, tests evenness with the remainder operator, and applies either division by 2 or `3n + 1`.
- Bash arithmetic expressions in double parentheses can update variables without a dollar sign, for example `((val = val / 2))`.
- A Bash for-each loop uses `for name in values`; the values are treated as a sequence of strings, with the loop variable set to one string per iteration.
- An unquoted variable expansion such as `$str` undergoes word splitting, so a string containing spaces becomes multiple loop items.
- Quoting the same expansion, as in `"$str"`, prevents word splitting and makes the entire value a single item.
- Use unquoted expansion deliberately when splitting is intended, rather than assuming a Bash string behaves like a structured list.
- A glob such as `scripts/loops/*.sh` expands to matching filenames, allowing a for-each loop to process scripts one at a time.
- If a glob has no matches, Bash may leave the pattern unchanged, causing a loop to run once with a literal value such as `*.pdf`.
- Brace expansion can generate a list of strings, while `seq` can produce numeric sequences for a for-each loop.
- For counting operations, Burton Ma recommends Bash's C-style loop rather than using `seq`; its three sections initialize a variable, test a condition, and update the variable.
- Bash counting loops use `for (( initialization; condition; update ))`, with arithmetic expressions inside double parentheses.
- A countdown from 10 through 0 initializes `i=10`, continues while `i >= 0`, and decrements with `i--`.
- This syntax resembles Java's counting loop but does not require declaring a variable type.
- Although Bash loop forms can often replace one another, the C-style form is the most direct choice for counting.
- The quoted expansion `"$@"` preserves each positional argument as a separate item, including filenames or values that contain spaces.
- An unquoted `$@` can split arguments containing spaces into extra words, so a script given three arguments may mistakenly process more than three items.
- The `shift` command moves positional parameters left; a `while` loop can process `$1`, call `shift`, and continue while `$#` is greater than zero.
- A `for` loop over `"$@"` and a `while` loop combined with `shift` are both ways to process command-line arguments one at a time.
- A loop of the form `while IFS= read -r line; do ...; done < file` reads a text file one line at a time.
- The `-r` option makes `read` treat backslashes as ordinary characters instead of escape characters.
- A line beginning with `#` can be skipped with a regular-expression test and `continue`, for example when ignoring a file header.
- Setting `IFS=,` lets `read` split comma-separated lines into variables such as student number, last name, and first name.
- Bash functions behave much like commands: they can receive arguments and have an exit status.
- The portable declaration form is `name() { ... }`; the `function name { ... }` form is also supported in Bash but is not portable across all shells.
- Function bodies use braces, and required spacing and line breaks matter; ShellCheck can identify syntax errors such as a missing space after `{`.
- Call a function by writing its name like a command, optionally followed by arguments, for example `greet` or `greet a b c`.
- Inside a function, `$1`, `$2`, and `$3` refer to that function's arguments, while `$#` gives the number of arguments passed to it.
- Bash functions do not declare a parameter list; they access arguments through the same positional-parameter syntax used by scripts.
- The script's positional parameters remain distinct from a function's parameters: after the function call, the script still retains its original `$1`, `$2`, and `$#` values.
- The lecture closes by noting that function return values and variable scoping require further explanation.
Transcript excerpt
0:01 Right. Good afternoon everybody. Uh the topic of today's lecture um is uh loops. Um so from your previous programming courses in Python and Java uh you would have seen a for loop almost certainly. Um so you would have seen two versions of a for loop. You would have seen a for each loop which you would have seen in Python. Uh and you would have seen a counting style loop which you would have seen in Java. Uh, and of course in Python, you emulate a counting style loop using a for each loop. Uh, depending on exactly what you covered in your Java course, you might have seen a while loop. Uh, and you probably did not see a dowh loop. Um, which is fine. So, bash has a for loop. Uh, it looks a lot like
0:50 a for each loop. So, it looks similar to Python's for loop. Uh, bash also has a counting style loop. So, similar to the Java style loop, here it says C style, but the Java inherited its syntax from C. U bash has a while loop. So, while some condition is true, loop. Uh, and it also has an until loop. So, until some condition is true, loop, right? And until is a bit unusual. Um, uh, it's the only programming language I know of that has one. Um there are probably others though that do have an until loop. Uh Java also has a dowhile loop. Uh but bash doesn't have one of those. Okay. So just like in Java or uh Python, break and continue are uh the usual
1:38 keywords inside of a loop, right? So break will break out of a loop. Uh continue will stop the current loop iteration and go to the next loop iteration just like it does in Python
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Burton Ma.