The FOR statement

Syntax

Loop over a list of values

for item [in list]; do
  command
done

Arithmetic loop

for (( initial_value; condition; increment )) do
  command
done

Discussion

  • command may be a single command or multiple commands, which are either placed on different lines or divided by ; on the same line.
  • If expansion of list is empty, then no command is executed.
  • In a loop over a list of values, the in list part is optional and when omitted the positional parameter $@ is assumed. See also: the $@ entry in the Built-in Shell Variables page.
  • In the arithmetic for loop the initial_value is evaluated. While the condition in true, the body of the loop with the command is executed. Then the increment is made.
  • Any of the expressions in an arithmetic for loop may be omitted. A missing condition is treated as being true. Therefore ((;;)) is an eternal loop, but we advise to avoid this and to use instead a while loop.
  • In an arithmetic for loop a ; before do is not necessary.
  • The arithmetic for loop has been introduced with Bash version 2.04 on 2000-03-21.
  • The built-in break command exits from the loop. If a parameter n is provided, then it breaks out of n nested loops.
  • The built-in continue command skip the remaining instructions in the loop, resuming with the next iteration of the loop. If a parameter n in provided, then it skips n nested loops.

Examples

#!/usr/bin/env bash

# Compute a frame MD5 checksum manifest for each audio-visual file in a folder

path_to_folder="${1}"
files_in_folder="$(ls "${path_to_folder}")"

for input_file in ${files_in_folder}; do
  path_to_file="${path_to_folder}/${input_file}"
  ffmpeg -i "${path_to_file}" -f framemd5 "${path_to_file}_frame.md5"
done
for ((i=1; i<=10; i++)) do echo "${i}"; done
for i in {1..5}; do echo "${i}"; done
# Bash 4 or greater is needed for ranges with step size:

for i in {1..30..7}; do echo "${i}"; done

# The same, coded to run also on very older Bash versions (actually since 2.04
# or since 2000-03-21):

for ((i=1; i<=30; i+=7)) do echo "${i}"; done
# BTW: an arithmetic for loop can be other than decimal

for ((i=0; i<=0xffff; i++)) do printf '%04x\n' ${i}; done > hex.txt

# The following command without the loop does the same much faster:

printf '%04x\n' {0..65535} > hex.txt
# If an interval range starts with two zeroes, then its value is of the octal
# numeral system. Therefore you may need to force it to decimal:

first_number='00000001'
last_number='00043200'

for ((n=((10#${first_number})); n<=((10#${last_number})); n++)) do
  printf '%08d\n' "${n}"
done

2022-01-29