for
Iterate over a list of items
TLDR
Iterate through command line arguments
Execute the given commands for each of the specified items
Iterate over a given range of numbers
Iterate over a given list of files
Iterate over a given list of directories
Perform a given command in every directory
SYNOPSIS
for variable in list; do commands; done
PARAMETERS
variable
The name of the variable that will hold the current item from the list during each iteration of the loop.
list
A sequence of items or a command whose output provides the items to iterate over. The items are typically separated by spaces, newlines, or other delimiters.
commands
One or more commands to be executed during each iteration of the loop. These commands can reference the variable to perform operations based on the current item. All commands between do and done will be executed.
DESCRIPTION
The for command in Linux is a control flow statement that allows you to iterate over a list of items or a range of values. It's a powerful tool for automating repetitive tasks within shell scripts or directly on the command line. The for loop repeatedly executes a block of code for each item in the specified list. This is incredibly useful for processing multiple files, executing commands with varying parameters, or performing iterative calculations.
The basic syntax involves defining a variable that will represent the current item in each iteration, providing the list of items to iterate over, and then specifying the commands to be executed within the loop. This command can be used to greatly simply command line logic and scripts.
EXAMPLES
- Looping through files:
for file in *.txt; do echo "Processing $file"; done
- Looping through a range of numbers:
for i in {1..5}; do echo "Number: $i"; done