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.
- Concepts
- Questions
- Sort and link
- 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 3runs three iterations;for i in $(seq 3 6)runs four, with3,4,5then6.What does this script print?
```bash
i=0
while [ $i -lt 5 ]; do
i=$((i + 2))
done
echo $i`6542,4then6
Show the answer
6itakes 0, 2, 4 then 6. The condition is only tested at the start of each iteration: at 4 it is true,ibecomes 6, and on the next iteration it is false.The body of a
forloop sits between … and ….Show the answer
The body of a
forloop sits between do and done.doopens the body anddonecloses it, forfor,whileanduntilalike.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 ]anduntil [ $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
forwithwhile, which does not split words - Use single quotes:
for f in '$(ls *.txt)' - Write
for f in *.txtand quote"$f"in the loop body
Show the answer
Write
for f in *.txtand quote"$f"in the loop bodyThe splitting comes from the result of
$(ls)being re-read by the shell. The wildcard supplies whole names. Quoting"$f"avoids a second split inmv.- Write