You are here: >

Linux and Unix for, foreach and repeat functions

for commandAbout for, foreach and repeat
for, foreach and repeat syntax
for, foreach and repeat examples
Related commands
Linux and Unix main page

About for, foreach, and repeat

for is a built-in shell function which performs a loop, iterating an action or set of actions a number of times.


The for keyword indicates a for loop. A for loop is a programming language statement which allows code to be repeatedly executed. Unlike other types of loops, such as the while loop, for loops are typically used when the number of iterations is known before entering the loop.

The syntax above describes how to use a for loop in Linux/Unix which can be executed at the command line or inside a shell script.

for, foreach and repeat syntax

for WORD [ in WORDLIST ... ] ; do ACTIONS ; done

for, foreach and repeat examples

for file in *.txt ; do wc -l $file ; done

Performs a word count of all files in the current directory with the extension .txt, and returns results similar to the following:

5 myfile.txt 
2 myfile2.txt 
14 newfile.txt 

break — Break out of a while, for, foreach, or until loop.
csh — The C shell command interpreter.
ksh — The Korn shell command interpreter.
sh — The Bourne shell command interpreter.