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

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

Description

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 often used when the number of iterations is known before entering the loop.

  • Description
  • Syntax
  • Examples
  • Related commands
  • Linux commands help

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.

Syntax

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

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.