Linux Command Reference ยท Bash Syntax
Bash for loop
Reference for the Bash for loop: iterate over words, globs and arrays, count with brace ranges and the C-style (( )) form, and avoid word-splitting mistakes.
The for loop repeats a block of commands once for each item in a list. Bash has two forms: the list form (for name in words; do ...) which assigns each word to a variable, and the arithmetic form (for ((init; test; step)); do ...) which works like the for of C.
The list is expanded first, so brace expansion, globs, command substitution and array expansions all produce items. Quoting decides how items are split, which is the source of most for bugs.
for name in word1 word2 word3; do commands done for ((i = 0; i < 5; i++)); do commands done
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
for name [in word ...]; do list; done for (( expr1 ; expr2 ; expr3 )); do list; done
| Part | Description |
|---|---|
name |
Variable set to each word in turn. It is a normal variable, not local to the loop. |
in word ... |
Words to iterate over, after all expansions and word splitting. If in is left out, the positional parameters "$@" are used. |
expr1 |
Arithmetic expression run once before the first test. |
expr2 |
Arithmetic expression evaluated before each pass; the loop ends when it is zero. An empty expr2 counts as true (infinite loop). |
expr3 |
Run after each pass. |
Returns: the status of the last command run in the body, or 0 if the body never ran.
Usage notes
- Quote expansions that may contain spaces:
for f in "${files[@]}"andfor f in *.txtare safe;for f in $(ls)splits on whitespace and breaks on names with spaces. - A glob that matches nothing stays as the literal pattern (
*.zzz) unlessshopt -s nullglobis set. Check with[[ -e $f ]]or usenullglob. - Brace expansion happens before variables, so
{1..$n}does not work. Usefor ((i = 1; i <= n; i++))orseq 1 "$n". - Brace ranges with leading zeros (
{01..10}) and steps ({0..20..5}) are supported in Bash 4+. - For reading lines of a file use
while read, notfor line in $(cat file): the latter splits on every space and expands globs. - Inside the C-style form, variables need no
$and spacing is free. It runs in the current shell, as does the list form; only a pipeline puts the loop in a subshell. breakandcontinuework in both forms; see break and continue.- Changing the loop list inside the body has no effect, since the list is expanded once. Changing the counter in the C-style form does.