for loops over words
A for loop repeats a body of commands once for each item. Use for item in words; do commands; done. Bash expands the list before entering the loop, assigns each resulting word to item, and runs the body. do starts the body and done ends it. Quoted multiword values remain one item; an explicit quoted empty string is also an item. When in words is omitted, the loop uses the positional arguments, as if you had written in "$@". If the list is empty, the body never runs. The loop variable is not automatically local: after a nonempty loop it normally retains the last assigned value. Use a meaningful name and quote its expansion in the body. With an empty list, the existing loop variable is not reassigned and the loop status is zero. Changes to the original positional parameters inside a word-list loop do not change the already expanded list.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Repeat fixed labels
Expected stdout:
alphabetagammaOne line per supplied word.
Keep spaces and empty values
for item in 'daily report' '' backup; do printf '[%s]\n' "$item"doneExpected stdout:
[daily report][][backup]The quoted phrase and empty string each count as one item.
Iterate over script arguments
set -- 'one file' twofor item; do printf '[%s]\n' "$item"doneprintf 'last=%s\n' "$item"Expected stdout:
[one file][two]last=twoset -- sets positional arguments for the practice shell. Omitting in preserves their boundaries.
Common mistakes
Do not put a whole list in one quoted string when you intend several iterations. for item in "red blue" runs once; for item in red blue runs twice.
Practice
Print three task labels, including daily report as one label and an empty label. Surround each with brackets. Predict the number of output lines. Then use an empty positional-argument list and verify zero iterations.
Next: while and until