Bash foreach loop examples for Linux / Unix

www.la‮tu‬turi.com
Bash foreach loop examples for Linux / Unix

The for loop is a common feature in Bash and other programming languages that allows you to run a block of code repeatedly with different values. Here are some examples of how to use the for loop in Bash to iterate over a range of numbers, the values of an array, and the lines of a file:

  1. Loop over a range of numbers:
for i in {1..10}; do
  echo $i
done

This will output the numbers 1 to 10, with each number on a separate line. The {1..10} syntax is used to specify a range of numbers, and the $i variable is used to access each value in the loop.

  1. Loop over the values of an array:
my_array=(apple banana cherry)

for value in ${my_array[@]}; do
  echo $value
done

This will output the values of the my_array array, with each value on a separate line. The ${my_array[@]} syntax is used to expand the array and provide a list of its values to the for loop. The $value variable is used to access each value in the loop.

  1. Loop over the lines of a file:
while read -r line; do
  echo $line
done < myfile.txt

This will read the lines of the myfile.txt file and output them, with each line on a separate line. The read command is used to read each line of the file, and the $line variable is used to access the line in the loop.

These are just a few examples of how to use the for loop in Bash to iterate over different types of values. Consult the Bash documentation for more information about using the for loop in Bash.

Created Time:2017-10-16 14:38:39  Author:lautturi