--- layout: page category-page: scripts category-title: Scripting tags: loop for while range do author: Marco Tereh title: Loops --- A very useful feature for scripting is loops; that is, the ability to write a repeating piece of code.
Loops take this form:
  [condition] do
    [repeated code]
  done
In particular, there are two types of loops, for loops and while loops.
For loops are written like this:
  for [variable] in [list] do
    [code]
  done
Their function is to iterate over a list. The list can take various forms, but the variable will always be one of its elements. In particular, it will be the first element of the list on the first iteration and advance by one element in every iteration after that. Most importantly, it can be accessed from inside the repeating code.

The most basic kind of list is a numerical range, written like this:
  for i in {1..10}; do
    [code]
  done
{1..10} means "the list of every number between 1 and 10 (inclusive)". i is the variable that will hold one of these numbers in every iteration. Here's a simple example of how to use it:
  for i in {1..10}; do
    echo $i;
  done
$i is how you access the variable i. Ranges can also count backward like this: {10..1}. Another way to say what {1..10} means is "The numbers between 10 and 1, in increments of 1". What if you want increments of two, though? What if you want every even number in a range?
Numerical ranges also allow you to specify the size of the increments or decrements between each element in the list, more generally called the step size. Here's an example:
  for i in {0..10..2}; do
    echo $i;
  done