Scripts: loops

for over a list, wildcards or "$@", while and until, while read to read a file line by line, break and continue: tracing a loop and avoiding the trap of names containing spaces.

  • 25 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • For loop: what is it?

    Show the answer

    A loop that runs its body once per word of a list fixed at the start, storing that word in its variable on each iteration.

    for i in 1 2 3 runs three iterations; for i in $(seq 3 6) runs four, with 3, 4, 5 then 6.

  • What does this script print?

    ```bash
    i=0
    while [ $i -lt 5 ]; do
    i=$((i + 2))
    done
    echo $i
    `

    • 6
    • 5
    • 4
    • 2, 4 then 6
    Show the answer

    6

    i takes 0, 2, 4 then 6. The condition is only tested at the start of each iteration: at 4 it is true, i becomes 6, and on the next iteration it is false.

  • The body of a for loop sits between … and ….

    Show the answer

    The body of a for loop sits between do and done.

    do opens the body and done closes it, for for, while and until alike.

  • while and until loops: what is it?

    Show the answer

    Loops driven by a condition command: one repeats as long as it returns 0, the other repeats until it returns 0.

    while [ $n -gt 0 ] and until [ $n -le 0 ] describe the same loop: only the wording of the condition is inverted.

  • A renaming script breaks on "my report.txt", treated as two files. It starts with for f in $(ls *.txt). Which fix is enough?

    • Write for f in $(ls -1 *.txt), which puts one name per line
    • Replace for with while, which does not split words
    • Use single quotes: for f in '$(ls *.txt)'
    • Write for f in *.txt and quote "$f" in the loop body
    Show the answer

    Write for f in *.txt and quote "$f" in the loop body

    The splitting comes from the result of $(ls) being re-read by the shell. The wildcard supplies whole names. Quoting "$f" avoids a second split in mv.