Bash foreach loop examples for Linux / Unix

In Bash, the for loop can be used to iterate over a list of items. Here are some examples of using the for loop in Bash:

  1. Loop over a range of numbers:
for i in {1..10}; do
echo $i
done
  1. Loop over a list of items:
for i in item1 item2 item3; do
echo $i
done
  1. Loop over the contents of a file:
for i in $(cat file.txt); do
echo $i
done
  1. Loop over all files in a directory:
for i in /path/to/directory/*; do
echo $i
done
  1. Loop over command output:
for i in $(command); do
echo $i
done
  1. Loop over environment variables:
for i in $(env); do
echo $i
done

You can also use for loop with in keyword.

arr=("item1" "item2" "item3")
for i in "${arr[@]}"
do
echo $i
done

You can also use for loop with while loop

count=1
while [ $count -le 10 ]
do
echo $count
count=$((count+1))
done

These are just a few examples of how you can use the for loop in Bash. You can use the for loop to iterate over any list of items, whether they come from a file, a directory, a command, or any other source.

Leave a Comment