Bash For Loop Examples


for loop syntax

How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using for statement? How do I use three-parameter for loop control expression?

A ‘for loop’ is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

Numeric ranges for syntax is as follows:

for VARIABLE in 1 2 3 4 5 .. N do command1 command2 commandN done


for VARIABLE in file1 file2 file3 do command1 on $VARIABLE command2 commandN done


for OUTPUT in $(Linux-Or-Unix-Command-Here) do command1 on $OUTPUT command2 on $OUTPUT commandN done


How to Loop Between a Start and End Point

This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop:

#!/bin/bash for i in 1 2 3 4 5 do echo “Welcome $i times” done

Sometimes you may need to set a step value (allowing one to count by two’s or to count backwards for instance). Latest bash version 3.0+ has inbuilt support for setting up ranges:

#!/bin/bash for i in {1..5} do echo “Welcome $i times” done

Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:

#!/bin/bash echo “Bash version ${BASH_VERSION}…” for i in {0..10..2} do echo “Welcome $i times” done

Sample outputs:

Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

How to Skip Numbers in a Range

The previous example showed how to loop between a start and end point, so now we’ll look at how to skip numbers in the range.

Imagine you want to loop between 0 and 100 but only show every tenth number. The following script shows how to do just that:

#!/bin/bashfor number in {0..100..10}doecho "$number "doneexit 0

The rules are basically the same. There is a list, a variable, and a set of statements to be performed between do and done. The list this time looks like this: {0..100..10}.

The first number is 0 and the end number is 100. The third number (10) is the number of items in the list that it will skip.

The above example, therefore, displays the following output:

  • 0
  • 10
  • 20
  • 30
  • 40
  • 50
  • 60
  • 70
  • 80
  • 90
  • 100


Please enter your comment!
Please enter your name here