Lesson 21: Bash Loops
Our backup script backs up one directory. In DevOps — we have dozens. We'll add a for loop that iterates over all of them. `for dir in list; do ... done` runs the loop body once per value in the list. done (=do reversed) closes it. `while [ condition ]; do ... done` loops while the condition is true
for is like 'for each'. `for dir in /app /etc; do echo $dir; done` means: run echo for /app, then for /etc. done means we're done. while is like 'as long as' — keep running while the condition is true.
- for loop
- for var in list; do ... done — bash assigns each iteration the next item in the list. done closes the loop body. Useful for processing lists: servers, files, directories.
- while loop
- while [ condition ]; do ... done — loops while the condition is true. Common for counting with a counter, reading lines, or waiting for an event. Forget to update the counter = infinite loop.