0% found this document useful (0 votes)
98 views

Loop Control Structure

The document discusses various types of while loops in BASH including: 1) A basic while loop that iterates over a block of code until a condition is met. 2) Using a while loop to read through a file line by line. 3) Creating an infinite while loop without a condition to iterate indefinitely. 4) Using break and continue statements to control the flow of a while loop.

Uploaded by

chris
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

Loop Control Structure

The document discusses various types of while loops in BASH including: 1) A basic while loop that iterates over a block of code until a condition is met. 2) Using a while loop to read through a file line by line. 3) Creating an infinite while loop without a condition to iterate indefinitely. 4) Using break and continue statements to control the flow of a while loop.

Uploaded by

chris
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

While Loop

 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.  

The syntax of a while loop in BASH is something like below:

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

echo "Out of the loop"


Reading a file with a while loop  
We can read a file with a while loop in BASH.  
By parsing certain parameters to the while loop condition, we can iterate
over the file line by line or by other groups like characters or words.   

#!/usr/bin/bash

file=temp.txt

while read -r line;


do
echo $line
done < "$file"
We use the command read to actually fetch the lines or characters from the
file.
The read command is passed with -r argument which ignores the escaping
of characters if the \  appears and hence it is parsed as its.  
We read a line from a file mentioned after the done statement.
The read command reads a line from the mentioned file and the while
loops end when the last line from the file is read ( no line is left to read). 
This is how we can read the contents of the file using a while loop in
BASH. 
Infinite while loop
To create an infinite loop using a while loop statement, we don’t need to
put any condition in the while loop and hence the loop iterates infinitely.
The below is the example of an infinite while loop:
#!/usr/bin/bash

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

# the number 4 can be the limit to


# iterate the loop
while [ $i -le 4 ];
do
echo $i
((i++))
done
In the above example, we can see that the loop iterates a defined number
of times. As we have initialized the counter to 1 and the condition is to
iterate the loop till the iterator is less than or equal to the number in this
case 4. Thus, we can change the number in the condition as per our
requirement.
Read the command-line argument with getopts
options
 We can use getopts options to read the input from the command line
and if there are multiple arguments.
 we can check them and parse them one by one using a while loop.
 getopts is a tool to get user input from the command line.
 We can have multiple options to parse from the command line, and
using getopts and while loops, we can make a professional-looking
user input program.
#!/bin/bash

while getopts n:a: OPT


do
case "${OPT}"
in
n) name=${OPTARG};;
a) age=${OPTARG};;
*) echo "Invalid option"
exit 1;;
esac
done

printf "My name is $name and am $age years old\n"


In this case, we have two options namely, the name and the age, you can
have multiple options.
In this case, we have used -n for name and -a for age.
We also have a default or invalid case check to ensure we do not parse
wrong arguments.
We can assign the value of the option using the OPTARG variable which
parses the value provided to the option. 
The while loop here is used to iterate till there are no options passed from
the command line.
We check for the -n and -a option and iterate till the carriage return or
enter key is pressed and there are no further options to be parsed. 

 C-style while loop


We can use C-styled while loop in BASH, the variables need to be
evaluated with BASH style but the overall syntax feels like C.
We can use the operators like <,>,<= and so on in the condition of the
while loop and hence it is called like the C-styled while loop. 
#!/bin/bash

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

In this example, we have three columns.


we read the contents by assigning them to the variables a,b, and c.
it can be anything you like but remember to use them in the loop body.
We can select a particular column like b and a and can print or perform
any operations on them.
This won’t be reflected in the file though as they are just the local script
variables.
Writing to a file using a while loop

We can write to a file by user input in a while loop.


We can use the while loop to iterate till we manually exit out of the loop
using CTRL + D by saving changes to the file or by CTRL + C for
avoiding writing to the file.
We use the read command to input the text from the command line and
parse it to the file. 
#! /bin/bash

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

We can use the continue statement to do the opposite of the break


statement. It will jump to the start of the loop block and iterate again. This
can be used for skipping over certain commands for certain conditions and
hence allows a change in the flow of the loop. 
For example, If we have a variable initialized to 1 and we want to display
only the numbers divisible by five or in a certain pattern following a
condition, we can use continue statements to do just that. This allows
iterating over the loop in the desired manner.
#!/usr/bin/bash

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:

Until Loop with break and continue


This example uses the break and the continue statements to alter the flow
of the loop.
 break: This statement terminates the current loop and passes the
program control to the following commands.
 continue: This statement ends the current iteration of the loop, skipping
all the remaining commands below it and starting the next iteration.

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

# this is an infinite loop


until false
do
((count++))
if [[ $count -eq 25 ]]
then

## terminates the loop.


break
elif [[ $count%5 -eq 0 ]]
then

## terminates the current iteration.


continue
fi
echo "$count"

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

for var in word1 word2 ... wordN


do
Statement(s) to be executed for every word.
done

Here var is the name of a variable and word1 to wordN are sequences of


characters separated by spaces (words).
Each time the for loop executes, the value of the variable var is set to the
next word in the list of words, word1 to wordN.

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

for FILE in $HOME/.bash*


do
echo $FILE
done
The above script will produce the following result −
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

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 $@

echo "Executing script"


   
# the script is executed using the below command
# main.sh sample1 sample2 sample
# where sample1, sample2 and sample3 are the
positional arguments
# here $@ contains all the positional arguments.
 
for SAMPLE in $@
do
    echo "The given sample is: $SAMPLE"
done
Output:
$bash -f main.sh sample1 sample2 sample3
Executing script
The given sample is sample1
The given sample is sample2
The given sample is sample3

Example 7: Infinite loop


while true
do
  # Command to be executed
  # sleep 1 indicates it sleeps for 1 sec
  echo "Hi, I am infinity loop"
  sleep 1
done
Output:
$bash -f main.sh
Hi, I am infinity loop
Hi, I am infinity loop
Hi, I am infinity loop
.
.
.
.
It continues

Example 8: Checking for user input


CORRECT=n
while [ "$CORRECT" == "n" ]
do
  # loop discontinues when you enter y i.e.e, when
your name is correct
  # -p stands for prompt asking for the input

  read -p "Enter your name:" NAME


  read -p "Is ${NAME} correct? " CORRECT
done

Output:
$bash -f main.sh
Enter your name:Ironman
Is Ironman correct? n
Enter your name:Spiderman
Is Spiderman correct? Y

seq command in Linux


 seq command in Linux is used to generate numbers
from FIRST to LAST in steps of INCREMENT.
 It is a very useful command where we had to generate list of
numbers in while, for, until loop. 
Syntax:  
seq [OPTION]... LAST
or
seq [OPTION]... FIRST LAST
or
seq [OPTION]... FIRST INCREMENT LAST
Options:  
 seq LAST: When only one argument is given then it produces numbers
from 1 to LAST in step increment of 1. If the LAST is less than 1, then is
produces no output. 

 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. 
 

 seq -f “FORMAT” FIRST INCREMENT LAST: This command is


used to generate sequence in a formatted
manner. FIRST and INCREMENT are optional. 
 seq -s “STRING” FIRST INCREMENT LAST: This command is
uses  STRING to separate numbers.
 By default this value is equal to “\n”. 
 FIRST and INCREMENT are optional. 

 seq -w FIRST INCREMENT LAST: This command is used to


equalize width by padding with leading
zeroes. FIRST and INCREMENT are optional. 

 seq –help: It displays help information. 


 seq –version: It displays version information. 

 
 
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.

Linux uses special characters or symbols known as metacharacters that add


special meaning to a shell command with respect to file search and commands
connection.

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.

However, the function of each metacharacter differs depending on the command


you are using it with.

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. 

 $ Variable Substitution or expand the value of Variable.


 > used for Output Redirection.
 >> used for Output Redirection to append.
 < Input redirection.
 << used for input redirection and is also known as here document.
 * Match any number of characters, Substitution wildcard for zero or more
characters
 ? Match one character, Substitution wildcard for 1 character
 [] Match range of characters, Substitution wildcard for any character
between brackets
 `cmd` Replace cmd with the command to execute and will execute that,
Substitution wildcard for command execution
 $(cmd) Replace cmd with the command to execute and will execute that,
Substitution wildcard for command execution
 | Pipe is a Redirection to send the output of one command/program/process
to another command/program/process for further processing.
 ; Command separator is used to execute 2 or more commands with one
statement.
 || OR conditional execution of the commands.
 && AND conditional execution of the commands.
 () Groups the command in to one output stream.
 & executes command in the background and will display the assigned Pid.
 # to comment something.
 $ To expand the value of a variable.
 \ used to escape the interpretation of a character or to prevent that.
 

The Escape Character or Backslash

A Backslash(‘\’) is the bash escape character. Any character immediately


following the backslash loses its special meaning and any letter following the
backslash gains its special meaning. Enter the following commands in the
terminal. 
 
echo "Quotation"
echo \"Quotation\"
As it can be seen with the example that double quotes could be not printed
without backslash and with backslash as they lost their special meaning, so they
were printed. 
 

The Backslash Escaped Characters 


 
\a alert (bell) 
\b backspace 
\e an escape character 
\f form feed 
\n new line 
\r carriage return 
\t horizontal tab 
\v vertical tab 
\\ backslash 
\’ single quote 
\nnn the eight-bit character whose value is the octal value nnn (one to three
digits) 
\xHH the eight-bit character whose value is the hexadecimal value HH (one or
two hex digits) 
\cx a control-x character 
 
 

The Single Quotes

 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. 

 Some strings have a lot of special characters so it is hard to use a


backslash before every special character.
 Hence, if we will put the same string within single quotes, most of the
special characters will lose their special meanings. Enter the following
commands in the terminal. 
 
echo \<Welcome\>\<to\>\<geeksforgeeks\>
echo '<Welcome><to><geeksforgeeks>'

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. 
 

The Back Quotes

Back Quotes(“) are used to execute a command. Anything enclosed between


them will be treated as a command and would be executed. Open the terminal
and execute the following commands. 
 
hostname=`hostname`
echo $hostname
You can be seen from the example the hostname command gets executed and
the name gets stored in the variable. 
 
 

function command in Linux


Function is a command in linux which is used to create functions or methods. 
 
1.using function keyword : A function in linux can be declared by using
keyword function before the name of the function. Different statements can be
separated by a semicolon or a new line. 

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

# Define your function here


Hello () {
echo "Hello World $1 $2"
return 10
}

# Invoke your function


Hello Zara Ali

# Capture value returnd by last command


ret=$?

echo "Return value is $ret"


Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Return value is 10

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

# Calling one function from another


number_one () {
echo "This is the first function speaking..."
number_two
}

number_two () {
echo "This is now the second function speaking..."
}

# Calling function one.


number_one
Upon execution, you will receive the following result −
This is the first function speaking...
This is now the second function speaking...

Function Call from Prompt


You can put definitions for commonly used functions inside your .profile. These
definitions will be available whenever you log in and you can use them at the
command prompt.
Alternatively, you can group the definitions in a file, say test.sh, and then execute
the file in the current shell by typing −
$. test.sh
This has the effect of causing functions defined inside test.sh to be read and defined
to the current shell as follows −
$ number_one
This is the first function speaking...
This is now the second function speaking...
$
To remove the definition of a function from the shell, use the unset command
with the -f option. This command is also used to remove the definition of a variable to
the shell.
$ unset -f function_name
Array Basics in Shell Scripting
Array in Shell Scripting

 An array is a systematic arrangement of the same type of data.


 But in Shell script Array is a variable which contains multiple values may
be of same type or different type since by default in shell script
everything is treated as a string.
 An array is zero-based ie indexing start with 0.

How to Declare Array in Shell Scripting?


We can declare an array in a shell script in different ways.

1. Indirect Declaration

In Indirect declaration, we assigned a value in a particular index of Array


Variable. No need to first declare.

ARRAYNAME[INDEXNR]=value

2. Explicit Declaration

In Explicit Declaration, First We declare array then assigned the values.

declare -a ARRAYNAME

3. Compound Assignment

In Compount Assignment, We declare array with a bunch of values. We can


add other values later too.

ARRAYNAME=(value1 value2 .... valueN)


Or
ARRAYNAME=([indexnumber]=string [indexnumber]=string....
[indexnumber]=string)

Example:

ARRAYNAME=([1]=10 [2]=20 [3]=30)

To Print Array Value in Shell Script?


To Print All elements

[@] & [*] means All elements of Array.

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

To Print first element

# To print first element

echo ${arr[0]}        

echo ${arr}        

Output:
prakhar
prakhar

To Print Selected index element

echo ${ARRAYNAME[INDEXNR]}

# To print particular element

echo ${arr[3]}        

echo ${arr[1]}        

Output:
rishabh
ankit

To print elements from a particular index

echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX}

# To print elements from a particular


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

To print elements in range

echo $
{ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX:COUNT_
ELEMENT}

# To print elements in range

echo ${arr[@]:1:4}     

echo ${arr[@]:2:3}     

echo ${arr[0]:1:3}    

Output:
ankit 1 rishabh manish
1 rishabh manish
Rak

To count Length of in Array


To count the length of a particular element in Array.
Use #(hash) to print length of particular element

# Length of Particular element

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.

# Replacing Substring Temporary

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

To delete Array Variable in Shell Script?


To delete index-1 element

unset ARRAYNAME[1]

To delete the whole Array

unset ARRAYNAME

To Print the Static Array in Bash


1. By Using while-loop
${#arr[@]} is used to find the size of Array.

# !/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

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]
  
    # Increment the i = i + 1
    i=`expr $i + 1`
done
  
# To print array values 
# starting from index, i=0
echo "Output :"
i=0
  
while [ $i -lt $n ]
do
    echo ${a[$i]}
  
    # To increment index
    # by 1, i=i+1 
    i=`expr $i + 1`
done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5

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

You might also like