The for statement in bash
As the for statement is a loop statement, you may be interested to check the other loop statements of Bash
With a file.
Locate returns a list of file in one line separated by a space. This code use then the for_name_in_word loop
# with globing
for n in ./prefix**
do
echo $n
done
# With locate utility
for n in `locate myfile`
do
echo $n
done
for ((cnt=1; cnt <= 10; cnt++)); do
echo $cnt;
done
for n in {0..5}
do
echo "BASH_VERSINFO[$n] = ${BASH_VERSINFO[$n]}"
done
# BASH_VERSINFO[0] = 3 # Major version no.
# BASH_VERSINFO[1] = 00 # Minor version no.
# BASH_VERSINFO[2] = 14 # Patch level.
# BASH_VERSINFO[3] = 1 # Build version.
# BASH_VERSINFO[4] = release # Release status.
# BASH_VERSINFO[5] = i386-redhat-linux-gnu # Architecture
# (same as $MACHTYPE).
for name [ in word ] ; do list ; done
where list is a list of commands.
The list of words following in is expanded, generating a list of items.
The variable name is set to each element of this list in turn, and list is executed each time.
If the in word is omitted, the for command executes the list of command once for each positional parameter that is set.
The return status is the exit status of the last command that executes.
If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0.
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
How it works:
Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated.
If any expression is omitted, it behaves as if it evaluates to 1.
The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid.