Shell Scripting Tutorials: Looping & Iteration statatement using for loop



Loops are a programming construct which allow us to repeat a command or set of commands for each item in a list. As such they are key to productivity improvements through automation. Similar to wildcards and tab completion, using loops also reduces the amount of typing required (and hence reduces the number of typing mistakes).

Syntax of For Loop

Example of For Loop

There are some key points of ‘for loop’ statement:

  • Each block of ‘for loop’ in bash starts with ‘do’ keyword followed by the commands inside the block. The ‘for loop’ statement is closed by ‘done’ keyword.
  • The number of time for which a ‘for loop’ will iterate depends on the declared list variables.
  • The loop will select one item from the list and assign the value on a variable which will be used within the loop.
  • After the execution of commands between ‘do’ and ‘done’, the loop goes back to the top and select the next item from the list and repeat the whole process.
  • The list can contain numbers or string etc. separated by spaces.

How For Loop works?

Write Simple Shell Script using For Loop


#!/bin/bash
for i in 1 2 3 4 5
do
 echo "Hello $i"
done

Let’s inspect each element:

  • #!/bin/bash – shows that the code is a bash script
  • i – is a placeholder for a variable. Meanwhile, $i is the individual value of the variable. You can also write it as c/$c or by any other name
  • in – separates the variable and the items that follow
  • 1 2 3 4 5 –  is an example of items you want to perform the instruction on
  • do – is the keyword that starts the loops. It will then execute the instruction n times, with n being the total number of items. Here, the value of n is 5
  • echo “Hello: $i” – is the code which we will repeat n times. Remember quotation marks turn anything inside it into one variable.
  • done – stops the loop

Example Program

Rajesh Kumar
Follow me
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x