Arrays in linux shell scripting

In this topic, you will learn how to work with arrays in Linux.

Creating new array variable

When you create variable using [], you are actually creating array.
 
cities[0]=’Brisbane’
cities[1]=’Perth’

echo “Element at position 1 in an array”  ${cities[1]}

Alternatively, you an create array using below syntax.
 
declare -a cities=(Brisbane Perth)

Another way to create an array is by loading data from file using below syntax. In below example, cities array will be created by loading data from the file – “cities.txt” Note that each element is same as each line in a file.
 
cities=( `cat “cities.txt” `)

Adding elements in array

Adding new element in array is also very simple. For example – If you want to add element at position number 2, you can use below syntax.
 
cities[2]=’Perth’

Accessing elements in array

 
echo “Element at position 1 in an array”  ${cities[1]}

echo “All elements in an array”  ${cities[@]}

Finding the size of array

You can use below syntax to find total number of elements in an array.
 
echo “All elements in an array”  ${#cities[@]}

Removing elements in array

You can use below syntax to delete an element in array. Below statement will delete an element at position 2.
 
unset cities[2]

Copying elements in an array

You can use below syntax to copy array. Here elements of array cities are copied into array – “towns”
 
towns=(“${cities[@]}”)

Joining arrays

 
newarray=(“${cities[@]}” “${towns[@]}”)
echo ${newarray[@]}

Replacing the data of an element in array You can use below syntax to replace the contents of an element in an array.
 
echo ${cities[@]/Per/Ade}

Iterating through the array elements

 
for (( i=0;i<${#cities[@]};i++)); do
echo ${cities[${i}]}
done

Web development and Automation testing

solutions delivered!!