DEV Community

howtouselinux
howtouselinux

Posted on

Linux bash for loop

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

This is from Bash For Loop Examples In Linux

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)