Bash - For Statement


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


How to loop over a list of file

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

for n in `locate myfile`
    echo $n



for n in {0..5}
  echo "BASH_VERSINFO[$n] = ${BASH_VERSINFO[$n]}"
# 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

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 ))

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

First, the arithmetic expression expr1 is evaluated according to the rules described below under ARITHMETIC EVALUATION. The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. 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 expres- sions is invalid.

Powered by ComboStrap