for

for

The for loop in Unix-like operating systems is a fundamental control structure in shell scripting. It allows you to iterate over a list of items or the output of a command, performing a set of commands for each item. This can be highly useful for automating repetitive tasks.

Basic Syntax

for variable in list
do
  commands
done
  • variable: The name of the variable that will take on each value in the list, one at a time.

  • list: A list of items, which can be hardcoded values, the output of a command, or a range.

  • commands: The commands to execute for each item in the list.

Examples

Iterating Over a List of Values

for color in red green blue
do
  echo "Color: $color"
done

Output:

Iterating Over a Range of Numbers

Output:

Iterating Over the Output of a Command

Output:

Using C-style Syntax

Some shells, like bash, support a C-style syntax for for loops:

Output:

Practical Use Cases

Processing Files in a Directory

Backing Up Files

Renaming Files

Checking Services Status

Nested Loops

You can nest for loops to handle more complex scenarios:

Conclusion

The for loop is an essential tool in shell scripting, providing a way to automate repetitive tasks by iterating over lists of items or command outputs. By mastering the for loop, you can significantly enhance your ability to write efficient and effective shell scripts.

help

Last updated