Linux for Developers Course
Linux for Developers
/
Intermediate

Loops

Definition

Control structures (`for`, `while`) in Bash used to repeatedly execute a block of commands multiple times, either for every item in a list or until a condition is met.

Explain Like I'm New

The automated repetitive worker. Instead of typing `rm` 50 times to delete 50 files, you tell a loop 'For every file in this folder, delete it'.

Real World Example

A DevOps script needs to restart 3 different servers. `for SERVER in web1 web2 db1; do` ` ssh root@$SERVER 'systemctl restart app'` `done`

Common Use Cases

  • •Batch processing files
  • •Pinging multiple IP addresses

Interview Questions

basic

  • What two words define the beginning and end of the block of commands inside a `for` loop?

intermediate

  • When would you choose a `while` loop over a `for` loop in a Bash script?

Flash Cards

Question

Beginning and end words?

Click to reveal answer
Answer

`do` and `done`.

Question

While vs For?

Click to reveal answer
Answer

A `for` loop is used when you have a specific, finite list of items (like 5 file names). A `while` loop is used when you don't know how many times it will run (e.g., 'While the server is still turned off, sleep for 5 seconds and check again').