LinuxCommandLibrary

for

Iterate over a list of items

TLDR

Iterate through command line arguments

$ for [variable]; do [echo $variable]; done
copy

Execute the given commands for each of the specified items
$ for [variable] in [item1 item2 ...]; do [echo "Loop is executed"]; done
copy

Iterate over a given range of numbers
$ for [variable] in [{from]..[to]..[step]}; do [echo "Loop is executed"]; done
copy

Iterate over a given list of files
$ for [variable] in [path/to/file1 path/to/file2 ...]; do [echo "Loop is executed"]; done
copy

Iterate over a given list of directories
$ for [variable] in [path/to/directory1/ path/to/directory2/ ...]; do [echo "Loop is executed"]; done
copy

Perform a given command in every directory
$ for [variable] in */; do (cd "$[variable]" || continue; [echo "Loop is executed"]) done
copy

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

SEE ALSO

while(1), until(1), if(1), case(1)

Copied to clipboard