LESSON · 1 OF 5

for loops

for loops

The most common loop shape in shell scripts.

The list form

bash
for user in alice bob charlie; do
  echo "hello, $user"
done

Runs the body once for each word after in. Words are whitespace-separated.

Looping over glob results

bash
for file in /var/log/*.log; do
  echo "found: $file"
done

The shell expands the glob before the loop runs, so you get one iteration per matching file. No quoting or word-splitting issues.

Looping over arguments

bash
for arg in "$@"; do
  echo "processing $arg"
done

You saw this in the arguments topic. Standard pattern for scripts that accept multiple arguments.

C-style loops

Bash also supports the C-style form for counted iteration:

bash
for (( i=0; i<5; i++ )); do
  echo "step $i"
done

Same syntax as C or Java: init, condition, increment. Useful for numeric loops. (( is bash arithmetic, so no $ on variables and normal math operators work.

Ranges with brace expansion

bash
for i in {1..5}; do
  echo "$i"
done

{1..5} expands to 1 2 3 4 5 before the loop sees it. {a..e} works too. Handy for quick numeric ranges without the C-style noise.

Iterating over command output (with care)

bash
for host in $(cat hosts.txt); do
  ssh "$host" uptime
done

Works, but has an ugly failure mode: the file is read all at once, then word-split. If a line contains spaces, they become separate iterations. For file-based loops, while read (next node) is safer.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute