Linux for, foreach and repeat functions

Updated: 05/04/2019 by Computer Hope
for command

On Unix-like operating systems, the for command is a shell command which performs a loop, iterating an action or set of actions multiple times.

This page covers the bash built-in version of for.


The for keyword indicates a for loop. A for loop is a programming language statement that allows code to be repeatedly executed. Unlike other types of loops, such as the while loop, for loops are 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 WORD [ in WORDLIST ... ] ; do ACTIONS ; done


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.