Shell Scripting Tutorial – 7

Hello,

Bash loops are very useful. Loops allow us to take a series of commands and keep re-running them until a particular situation is reached. They are useful for automating repetitive tasks. There are 3 basic loop structures in Bash scripting

  1. While Loops

While an expression is true, keep executing these lines of code.

Code:

#!/bin/bash

counter=1

while [ $counter -le 10 ]
do
echo $counter

((counter++))
done

echo Bazinga

 

2) For Loop:

The for loop is a little bit different to the previous two loops. What it does is say for each of the items in a given list, perform the given set of commands. It has the following syntax.

for var in <list>
do
<commands>
done

The for loop will take each item in the list (in order, one after the other), assign that item as the value of the variable var, execute the commands between do and done then go back to the top, grab the next item in the list and repeat over.

The list is defined as a series of strings, separated by spaces.

Code:

#!/bin/bash

for x in audi bmw tata;do
echo $x
done

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s