Array in Shell Scripting: ARRAYNAME (INDEXNR) Value
Array in Shell Scripting: ARRAYNAME (INDEXNR) Value
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.
ARRAYNAME[INDEXNR]=value
2. Explicit Declaration
1.#! /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}
echo ${arr[0]}
echo ${arr}
echo ${arr[3]}
echo ${arr[1]}
echo ${arr[@]:0}
echo ${arr[@]:1}
echo ${arr[@]:2}
echo ${arr[0]:1}
echo ${arr[@]:1:4}
echo ${arr[@]:2:3}
echo ${arr[0]:1:3}
echo ${#arr[0]}
echo ${#arr}
7. # Size of an Array
echo ${#arr[@]}
echo ${#arr[*]}
o 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.
8.# Search in Array
echo ${arr[@]/*[aA]*/}
9. # Replacing Substring Temporary
echo ${arr[@]//a/A}
echo ${arr[@]}
echo ${arr[0]//r/R}
while loop
10. # !/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
For Loop
11.# !/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
To Read the array elements at run time and then Print the Array.
1. Using While-loop
12. # !/bin/bash
# To input array at run
# time 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
13. # !/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