In a shell script, a for loop allows you to iterate over a set of values or a range of numbers. Here are a few examples of how to use for loops in different contexts:

Example 1: Iterating Over a List of Values
#!/bin/bash

# List of values
for item in apple banana cherry
do
    echo "I like $item"
done
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
Example 2: Iterating Over a Range of Numbers
#!/bin/bash

# Range of numbers from 1 to 5
for i in {1..5}
do
    echo "Number $i"
done
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
Example 3: Iterating Over Files in a Directory
#!/bin/bash

# Directory path
directory="/path/to/directory"

# Iterate over files in the directory
for file in "$directory"/*
do
    echo "Processing $file"
done
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
Example 4: Using C-Style Syntax
#!/bin/bash

# C-style for loop, which is not avaiable in /bin/sh
for ((i = 1; i <= 5; i++))
do
    echo "Number $i"
done
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

You can save any of these scripts to a file (e.g., script.sh), make it executable with chmod +x script.sh, and run it with ./script.sh.