LOGBOOK

HELP

Quiz Entry - updated: 2026.06.20

What is the syntax for a for loop in Bash?

for VAR in LIST; do COMMANDS; done — bash assigns each item of LIST to VAR in turn and runs the body once per item.

The defining feature of bash's for is that it iterates over a list of words, not a counter. That list can come from anywhere: literal words, a glob like *.txt (which bash expands to matching filenames), a brace range {1..5}, or command output via $(...). This makes "do something to every file/host/user" delightfully concise.

for VARIABLE in LIST; do
    COMMANDS
done

Examples:

# Loop over words
for name in Alice Bob Charlie; do
    echo "Hello $name"
done

# Loop over files
for file in *.txt; do
    echo "Processing $file"
done

# Loop over command output
for user in $(cat /etc/passwd | cut -d: -f1); do
    echo "User: $user"
done

# Loop with sequence
for i in {1..5}; do
    echo "Number: $i"
done

# C-style loop
for ((i=1; i<=5; i++)); do
    echo "Count: $i"
done

Using seq:

for i in $(seq 1 10); do
    echo $i
done

# Even numbers only
for i in $(seq 2 2 10); do
    # 2, 4, 6, 8, 10
    echo $i
done

Gotcha: for x in $(cat file) splits on whitespace, so a line containing spaces becomes multiple iterations. To loop over lines (preserving spaces), use while IFS= read -r line; do ...; done < file instead.

Tip: Globs like *.txt that match nothing expand to the literal text *.txt by default — guard with [ -e "$file" ] inside the loop if the directory might be empty.

From Quiz: LIOS / Bash Scripting and Automation | Updated: Jun 20, 2026