Loop Control Structure
Loop Control Structure
A while loop is a statement that iterates over a block of code till the
condition specified is evaluated to true.
We can use this statement or loop in our program when do not know
how many times the condition is going to evaluate to false before
evaluating to true.
while [ condition ];
do
# statements
# commands
done
If the condition is false then the commands inside the while block are
executed and are iterated again after checking the condition.
Also if the condition is true the statements inside the while block are
skipped and the statements after the while block are executed.
The example of a while loop is as follows:
#!/usr/bin/bash
a=7
while [ $a -gt 4 ];
do
echo $a
((a--))
done
#!/usr/bin/bash
file=temp.txt
while :
do
echo "An Infinite loop"
# We can press Ctrl + C to exit the script
done
Thus the while loop in the script is going to iterate for infinite time. We
can manually break the loop or the script by CTRL + C.
While loop to iterate for a fixed number of times
We can use a while loop to iterate over a fixed number of times, we can set
the condition to be -le or less than equal to a number, and the loop will
iterate till the iterator is less than or equal to the number provided in the
condition. Also, we need to increment the iterator manually so to keep the
loop iterator ticking, or else the loop will go on forever.
#!/usr/bin/bash
i=1
i=0
while((i < 12))
do
echo $i
((i+=2))
done
In this example, we can see that the while loop has a condition with non-
bash operators like -le, -ge, etc instead we use the C-styled operators in the
condition. The rest of the loop is the basic loop as in BASH, the variable
or iterator i is incremented by two as we can see in the last statement of the
loop body. Thus the loop iterates over 5 times.
While loop to perform operations on a file
We can perform operations on a file, like reading only a particular part of a
file. If we have columns that are formatted in a particular fashion, we can
use variables to assign them and print them one row data time.
#!/bin/bash
while read a b c
do
echo $b - $a
done < wh.txt
file=wh.txt
echo "Enter the content into the file $file"
while read line
do
echo $line >> $file
done
So from the example above, we were able to enter text into a file using a
while loop and read command.
To exit out of the loop and save changes to the file, we use the CTRL+ D
keys, and to exit out of the loop without saving anything into the file we
can use the CTRL + C keys. T
Thus we enter the text from the command line to the text file using the
read command and a while loop.
Break and continue
Break and continue are essential in a program that deals with loop
statements as they control the flow of the loop statements without any
explicit conditions.
Break statement
We use break statements to exit out of the loop without waiting for the
condition of the while loop to evaluate to true.
This statement can be used within a loop block.
This can be used to exit out of an infinite loop with a programmatic
condition inside the loop and thus maintain the control of the loop.
For example, we have a script that counts from 1 and forever. But we can
programmatically break out of the loop using a break statement inside the
body of the loop with a condition.
#!/usr/bin/bash
i=1
while :
do
echo $i
if [ $i -eq 20 ];
then
echo "This is end of the loop"
break
if
((i++))
done
From the script and the execution, we can see that we were able to break
or exit an infinite loop with a conditional statement and the break
statement.
Thus the break statement is used to get the control flow of a program/script
from inside a while loop to break out of the loop without the loop
condition evaluating to true.
Continue statement
i=1
while [ $i -lt 30 ];
do
((i++))
if [[ $(( $i % 5 )) -ne 0 ]];
then
continue
if
echo $i
done
As we can see the continue statement, jumps to the beginning of the block
and starts the execution of the commands by skipping the next commands
inside the block.
The while loop iterates for only the value of variable i being less than 30,
thus the if condition checks if the variable i is divisible by 5, and if it’s not
we iterate over again using continue and increment the value of the
variable i.
The variable i only gets echoed if it’s divisible by 5, thus the if condition
is evaluated to false and we do not encounter a continue statement and
carry with the normal flow of the loop.
This is done to avoid logging of every number and only print the numbers
which do not follow a pattern or condition in the if statement or other
conditional statements.
Until Loop
The Until loop is used to iterate over a block of commands until the
required condition is false.
Syntax:
until [ condition ];
do
block-of-statements
done
Here, the flow of the above syntax will be –
Checks the condition.
if the condition is false, then executes the statements and goes back to
step 1.
If the condition is true, then the program control moves to the next
command in the script.
Example:
#!/bin/bash
echo "until loop"
i=10
until [ $i == 1 ]
do
echo "$i is not equal to 1";
i=$((i-1))
done
echo "i value is $i"
echo "loop terminated"
Output:
Infinite Loop using Until
In this example the until loop is infinite i.e it runs endlessly. If the
condition is set in until the loop is always false then, the loop becomes
infinite.
Program:
#!/bin/bash
## This is an infinite loop as the condition is set
false.
condition=false
iteration_no=0
until $condition
do
echo "Iteration no : $iteration_no"
((iteration_no++))
sleep 1
done
Output:
Program
#!/bin/bash
## In this program, the value of count is
incremented continuously.
## If the value of count is equal to 25 then, the
loop breaks
## If the value of count is a multiple of 5 then,
the program
## control moves to the next iteration without
executing
## the following commands.
count=0
done
Output:
Until Loop with Single condition
This is an example of an until loop that checks for only one condition.
Program
#!/bin/bash
# This program increments the value of
# i until it is not equal to 5
i=0
until [[ $i -eq 5 ]]
do
echo "$i"
((i++))
done
Output:
Until Loop with Multiple conditions
Until loop can be used with multiple conditions. We can use the and :
‘&&’ operator and or: ‘||’ operator to use multiple conditions.
Program
#!/bin/bash
## This program increments the value of
## n until the sum is less than 20
## or the value of n is less than 15
n=1
sum=0
until [[ $n -gt 15 || $sum -gt 20 ]]
do
sum=$(($sum + $n))
echo "n = $n & sum of first n = $sum"
((n++))
done
Output:
Exit status of a command:
We know every command in the shell returns an exit status.
The exit status of 0 shows successful execution while a non-zero value
shows the failure of execution.
The until loop executes till the condition returns a non-zero exit status.
for loop
The for loop operates on lists of items.
It repeats a set of commands for every item in a list.
Syntax
Example
Here is a simple example that uses the for loop to span through the given
list of numbers −
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
Following is the example to display all the files starting with .bash and
available in your home. We will execute this script from my root −
#!/bin/sh
Example Programs
Example 1:
Implementing for loop with break statement
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the
loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Example 2:
Implementing for loop with continue statement
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a = 5 then continue the loop and
# don't move to line 8
if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10
Example 3:
Implementing while loop
a=0
# -lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
Example 4:
Implementing until loop
a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
10
Note: Shell scripting is a case-sensitive language, which means proper
syntax has to be followed while writing the scripts.
Example 5:
COLORS="red green blue"
# the for loop continues until it reads all the
values from the COLORS
for COLOR in $COLORS
do
echo "COLOR: $COLOR"
done
Output:
$bash -f main.sh
COLOR: red
COLOR: green
COLOR: blue
Example 6:
We can even access the positional parameters using loops
We execute a shell script named sample.sh using three parameters
Script Execution: main.sh sample1 sample2 sample3
We can access above three parameters using $@
Output:
$bash -f main.sh
Enter your name:Ironman
Is Ironman correct? n
Enter your name:Spiderman
Is Spiderman correct? Y
seq FIRST LAST: When two arguments are given then it produces
numbers from FIRST till LAST is step increment of 1. If LAST is less
than FIRST, then it produces no output.
seq FIRST INCREMENT LAST: When three arguments are given
then it produces numbers from FIRST till LAST in step
of INCREMENT. If LAST is less than FIRST, then it produces no
output.
Shell Meta characters
The most powerful feature of the Linux Bash shell is its capability to work
around files and redirect their input and output efficiently.
Metacharacters: These are the special characters that are first interpreted by the
shell before passing the same to the command. They are also known as shell
wildcards.
The metacharacters are helpful in listing, removing, and copying files on Linux.
Sometimes they are used to perform an action while other times they are just
used as a character, so the quoting mechanism performs this task it makes us
use them in whatever way we want to.
Single Quotes are used to preserve the literal value of each character
within the quotes.
A single quote may not occur between single quotes, even when preceded
by a backslash.
All special characters within the single quotes lose their special
meanings.
You can be seen from the example that we had to use a lot of backslash in the
first statement which made it complex. While with single quotes output was
same without using backslash
The Double Quotes
Double Quotes(“”) preserves the literal value of all characters within the
quotes, with the exception of ‘$’, ‘`’, ‘\’, and when history expansion is enabled,
‘!’. The backslash retains its special meaning only when followed by one of the
following characters: ‘$’, ‘`’, ‘”’, ‘\’, or newline. Enter the following commands
in the terminal.
name=geeksforgeeks
echo '$name'
echo "$name"
You can be seen that in the case of single quotes the value of the variable was
not printed while in the case of double quotes the value of the variable was
printed.
SYNTAX
function name { COMMANDS ; }
2.using parenthesis : A function can also be declared by using parenthesis after
the name of the function. Different statements can be separated by a semicolon
or a new line.
SYNTAX
name () { COMMANDS ; }
3.Parameterised function :
$1 will displays the first argument that will be sent and $2 will display the
second ans so on…
4.help function : It displays help information.
Returning Values from Functions
If you execute an exit command from inside a function, its effect is not only to
terminate execution of the function but also of the shell program that called the
function.
If you instead want to just terminate execution of the function, then there is way to
come out of a defined function.
Based on the situation you can return any value from your function using
the return command whose syntax is as follows −
return code
Here code can be anything you choose here, but obviously you should choose
something that is meaningful or useful in the context of your script as a whole.
Example
Following function returns a value 10 −
#!/bin/sh
Nested Functions
One of the more interesting features of functions is that they can call themselves and
also other functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
#!/bin/sh
number_two () {
echo "This is now the second function speaking..."
}
1. Indirect Declaration
ARRAYNAME[INDEXNR]=value
2. Explicit Declaration
declare -a ARRAYNAME
3. Compound Assignment
Example:
echo ${ARRAYNAME[*]}
Example:
#! /bin/bash
# To declare static Array
arr=(prakhar ankit 1 rishabh manish abhinav)
# To print all elements of array
echo ${arr[@]}
echo ${arr[*]}
echo ${arr[@]:0}
echo ${arr[*]:0}
Output:
prakhar ankit 1 rishabh manish abhinav
prakhar ankit 1 rishabh manish abhinav
prakhar ankit 1 rishabh manish abhinav
prakhar ankit 1 rishabh manish abhinav
echo ${arr[0]}
echo ${arr}
Output:
prakhar
prakhar
echo ${ARRAYNAME[INDEXNR]}
echo ${arr[3]}
echo ${arr[1]}
Output:
rishabh
ankit
echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX}
echo ${arr[@]:0}
echo ${arr[@]:1}
echo ${arr[@]:2}
echo ${arr[0]:1}
Output:
prakhar ankit 1 rishabh manish abhinav
ankit 1 rishabh manish abhinav
1 rishabh manish abhinav
Prakhar
echo $
{ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX:COUNT_
ELEMENT}
echo ${arr[@]:1:4}
echo ${arr[@]:2:3}
echo ${arr[0]:1:3}
Output:
ankit 1 rishabh manish
1 rishabh manish
Rak
echo ${#arr[0]}
echo ${#arr}
Output:
7
7
To count length of Array.
# Size of an Array
echo ${#arr[@]}
echo ${#arr[*]}
Output:
6
6
To Search in Array
arr[@] : All Array Elements.
/Search_using_Regular_Expression/ : Search in Array
Search Returns 1 if it found the pattern else it return zero. It does not alter the
original array elements.
# Search in Array
echo ${arr[@]/*[aA]*/}
Output:
1
To Search & Replace in Array
//Search_using_Regular_Expression/Replace : Search &
Replace
Search & Replace does not change in Original Value of Array Element.
It just returned the new value. So you can store this value in same or
different variable.
echo ${arr[@]//a/A}
echo ${arr[@]}
echo ${arr[0]//r/R}
Output:
prAkhAr Ankit 1 rishAbh mAnish AbhinAv
prakhar ankit 1 rishabh manish abhinav
RakhaR
unset ARRAYNAME[1]
unset ARRAYNAME
# !/bin/bash
# To declare static Array
arr=(1 12 31 4 5)
i=0
# Loop upto size of array
# starting from index, i=0
while [ $i -lt ${#arr[@]} ]
do
# To print index, ith
# element
echo ${arr[$i]}
# Increment the i = i + 1
i=`expr $i + 1`
done
Output:
1
12
31
4
5
2. By Using for-loop
# !/bin/bash
# To declare static Array
arr=(1 2 3 4 5)
# loops iterate through a
# set of values until the
# list (arr) is exhausted
for i in "${arr[@]}"
do
# access each element
# as $i
echo $i
done
Output:
1
12
31
4
5
To Read the array elements at run time and then Print the Array.
1. Using While-loop
# !/bin/bash
# To input array at runtime by using while-loop
# echo -n is used to print
# message without new line
2. Using for-loop
# !/bin/bash
# To input array at run
# time by using for-loop
echo -n "Enter the Total numbers :"
read n
echo "Enter numbers:"
i=0
# Read upto the size of
# given array starting
# from index, i=0
while [ $i -lt $n ]
do
# To input from user
read a[$i]
# To increment index
# by 1, i=i+1
i=`expr $i + 1`
done
# Print the array starting
# from index, i=0
echo "Output :"
for i in "${a[@]}"
do
# access each element as $i
echo $i
done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5