For Loops

A for loop repeats commands once for each item in a list of arguments. The general format of a for loop is:

for index in list
do
    commands
done

The index is a variable name. It takes on a value from the list with each iteration of the loop. The list is a list of arguments through which for loops. A simple for loop is:

for name in John Sam Paul
do
    echo $name
done

Items in the list can be separated by a space or by the end of a line.

You can provide the for loop with a list of arguments by executing a command. For instance, the following script processes the output of the date command.

#!/bin/bash
# Script name: splitdate - outputs parts of the date in a column
for part in `date`
do
    echo $part
done

When you run the script, you see: ...

Get Spring Into Linux® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.