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
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
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
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
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
.