LinuxCommandLibrary

for

Iterate over a list of items

TLDR

Iterate through command line parameters

$ for [variable]; do [echo $variable]; done
copy

Execute the given commands for each of the specified items
$ for [variable] in [item1 item2 ...]; do [echo "Loop is executed"]; done
copy

Iterate over a given range of numbers
$ for [variable] in [{from..to..step]}; do [echo "Loop is executed"]; done
copy

Iterate over a given list of files
$ for [variable] in [path/to/file1 path/to/file2 ...]; do [echo "Loop is executed"]; done
copy

Iterate over a given list of directories
$ for [variable] in [path/to/directory1/ path/to/directory2/ ...]; do [echo "Loop is executed"]; done
copy

Perform a given command in every directory
$ for [variable] in */; do (cd "$[variable]" || continue; [echo "Loop is executed"]) done
copy

SYNOPSIS

for name [in word ...] ; do command_list ; done

for (( expr1 ; expr2 ; expr3 )) ; do command_list ; done

DESCRIPTION

The for loop is a core Bash shell construct for iterating over a sequence of words, assigning each to a variable and executing commands within the loop body. It supports two main forms: the classic word-list iteration and the arithmetic C-style loop.

In the classic form, for name [in words]; do commands; done, it processes each word (from the list or positional parameters if omitted), setting name accordingly. Words can come from brace expansion {1..10}, globs *.txt, command substitution $(seq 5), or $@.

The arithmetic form, available in Bash, Ksh, and Zsh, is for ((init; condition; update)); do commands; done. It evaluates arithmetic expressions, similar to C: for ((i=0; i<10; i++)).

Common in scripts for batch processing files, generating sequences, or handling arguments. Loops run in the current shell context, with name expanded in commands. Early termination uses break; skipping uses continue. POSIX-compliant in classic form, but arithmetic is an extension.

CAVEATS

Builtin shell construct, not an executable ("type for" shows shell function). Classic form POSIX; arithmetic non-portable. List undergoes word splitting/globbing unless quoted. Infinite loops possible if condition false.

CLASSIC EXAMPLE

for file in *.log; do echo "Processing $file"; done
Iterates over .log files.

ARITHMETIC EXAMPLE

for ((i=1; i<=5; i++)); do echo "Count: $i"; done
Outputs numbers 1 to 5.

OVER ARGUMENTS

for arg; do echo "Arg: $arg"; done
Loops over script positional parameters ($@).

HISTORY

Originated in Bourne shell (1977) for word iteration. Arithmetic C-style added in Korn shell (ksh88, 1988); Bash adopted in version 2.0 (1996). Evolved for scripting efficiency in Unix-like systems.

SEE ALSO

seq(1), find(1), bash(1)

Copied to clipboard