Pages

Scripting - Looping

Looping in Scripts 

Let us say that we want to create 100 files, by the name file1,file2,file3...,file100. 
We could  execute the command "touch" with the file name a 100 times manually, which is a very time consuming and inefficient way of doing it. 
In scripting we have a work around for such repetitive job, loops. 

Loops are use when we want to execute a specific set of commands repeatedly a certain number of times or until some condition is not satisfied. 

Bash scripting provides us with the following kinds of loops 

for 
while
until

for : 

The syntax of the "for" loop is 

for  "var" in "list
do

{ block of commands to be executed } 
done 

e.g.: 

#!/bin/bash

for i in 1 2 3
do 
echo $i
done. 

Save the file as first.sh,give execute permission to the script and run it. 
The above example would give the output 
1
2
3

In the "for" loop we pass a list after the "in" keyword. The list can be list of any kind, each time one value of the list would be assigned to the variable and the loop will be executed. 
In the above example shown above, the first time the list was executed "1" was assigned to the variable "i", second time "2" was assigned and so on. 
The length of the list is not fixed, it can be as long as you want. 

e.g.:

for i in *
do 
echo $i
done 

Save the file as for2.sh, give execute permission and run it. 

In the above example we have used "*" in place of the list. 
What this does is repeatedly  assign the name of the files and folders in the present working directory to the variable "i". Thus when the loop executes, the script would act like the "ls" command and list out the contents of the present working directory. 

Bash also provides a special kind of "for" loop, which you would be familiar if you have done "c" programming. 

The syntax of this "for" loop is 

for(("initialise variable";"some conditional statement";"incrementing the variable"))
do
{Block of commands to be executed} 
done

e.g.: 

#!/bin/bash
for((i=0;i<10;i=i+1))
do
echo $i
done

Save the file as for3.sh, Give execute permission and run it.   

In the above format of the for loop, note that we need two "(".  
The first expression is initialising a variable to a value from which we want to start counting. In the above example we have initialised "i" to 0. 

The second expression is a conditional statement, the "for" loop  will keep executing as long as this statement is true. In the above example we have used the condition "i<10", which means keep executing the loop as long as the value of "i" is less than 10. 

The third expression is the value by which the variable should change each time a new iteration of the loop is started. In the above example we have used "i=i+1", which means we are increasing the value of "i" by one each time the for loop begins. 

So the above script will run the command "echo" 10 times, each time incrementing the value of "i" by 1. 

Note that the above format of the for loop is specific to bash, so if you want to run it with out giving the execute permission you will have to use "bash for3.sh" and not "sh for3.sh". 

While loop:

Syntax for while loop. 

while("condition statement")
do

{block of commands to be executed}
done 

The while loop is used when do not know the exact count of number of times we want to
execute the loop,but the loop execution is dependent on certain condition. 
As long as the condition being tested in the conditional statement is true, the loop will keep executing. 
The condition statement is implemented using the "test" command,as shown in the article  "Conditional Statements"

 eg: 

#!/bin/bash 
i=0
while[ $i -lt 5 ]
do 
echo $((i++)) 
done
echo "End of Loop"

Save the above script as while.sh, give execute permission and run it. 
The script should produce the output 
0
1
2
3
4
End of Loop

Note that the increment operator works only in the bash and not in simple bourne shell. 

The loop keeps executing till the expression in the conditional statement of the while loop is true. "i" starts with a value of "0" and each time it enters the loop the value gets incremented. Once the value of "i" becomes 5 the expression "i -lt 5" turns out to be false the script stops entering the loop and jumps to the statement after the loop, i.e. the statement after the "done" statement. 


Until loop: 

The until loop works like opposite of the while loop.
Syntax: 

until [ "conditional statement" ]
do 

{"block of commands'} 
done 

The until loop will keep running as long as the expression in the conditional statement is false, once the expression returns true the loop will exit. 
e.g.: 


#!/bin/bash
i=0
until [ $i -gt 5 ]
do 
echo $((i++)) 
done
echo "End of Loop"

Save the above script as until.sh, give it execute permissions and run it. 
It should produce the following output
0
1
2
3
4
5
End of Loop 

The "i" starts from the value "0", the expression in the until checks if the value of "i" is greater than false, which is false and hence it enters the loop. Each time the loop is executed the value of "i" is incremented by 1. As soon as the value of "i" becomes six, the expression "$i -gt 5" becomes true. Thus the until loop exits. 

Break: 

The break statement in useful when you want to stop a loop from continuing execution. 

 e.g.: 

#!/bin/bash 
i=0
while [ 1 ]
do
echo $((i++))
if [ $i -eq 5 ]
then
break
fi
done

Save the above script as break.sh,give it execute permission and run it. The script should produce the output 

0
1
2
3
4

In the script we have used a "1" in the while loop condition,which means it will always be true, and will keep executing the loop for ever. The break statement comes handy in such situations, when you want to stop a infinite loop is certain condition is met.  
In the script above the value of "i" is compared in the if statement with the "5", and when the value of i becomes 5, the script enters the if block where the break is executed. This causes the script to jump out of the loop it is currently executing, thus ending the script. 

Continue: 

"Continue" is useful when you want to skip to begin of the loop with out executing some of the statements. 
 eg: 

#!/bin/bash 
i=0
while [ $((i++)) -lt 5 ]
do
if [ $i -eq 2 ]
then
continue
fi
echo $i
done

Save the above script as continue.sh, give it execute permission and run it. You should see the output 
1
3
4
5

The script keeps comparing the value of "i" with 2, and when the value becomes "2" it enters the if block where the "continue" gets executed which causes the script to skip to the beginning whit out executing the remaining statements in the script. That is why the value "2" does not get printed in the output while rest of them do get printed.  


Try it out: 
1. Write a script that will list out only the files in your current folder. (Hint use the "test" and the "for loop")
2. Write a script that will create a back up of every file in your directory in a subdirectory by the name "backup". 
3. Write a script that will list only the first 5 latest modified files in your current directory. 
(Hint: Use "for i in `ls -t`" along with "break") 
4. Write a script that will prompt the user for a file name, and search for the same in the current directory. If the file exists echo "File present" else echo  "File not found". 
5. Write a script that will give execute permission to all the files that end with the extension .sh. (Hint: use "for i in *.sh" )

No comments:

Post a Comment