Elements of Bash Array

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Working with the elements of an array in Bash is the foremost step in efficient data management using Scripts within arrays. So, this tutorial will discuss the ins and outs of the elements of an array in Bash, from accessing and modifying to even removing the elements along with Bash script development.

What Are the Elements of Array in Bash?

Array elements in Bash refer to the individual data values or items stored within the array and accessible through numerical indices in indexed arrays or user-defined keys in the associative arrays. Bash arrays can store data irrespective of type. It can store elements of only string type like the following array:

hello=("world" "universe" "multiverse")

On the other hand, it stores both strings and numbers in the same array like the following:

exceptional=(10 "hello" 3.14)

NOTE: Even when assigning numerical values, the Bash array stores them as strings by default. For example, the array numbers=(10 20 30 40 50) stores the elements “10” “20” “30” “40” “50” as strings and not any numeric data type. Bash doesn’t practice rigidity in terms of data type so it treats elements as strings within an array.

Thus, for any mathematical calculation, using explicit type conversion tools like “$((…))” or “expr” is recommended.

Access Array Elements

Accessing the array is the foremost step in working with the elements of an array in Bash. The length expressions ${array_name[@]} and ${array_name[*]} access the elements of array_name and print them on the screen using the echo command in a single line.

Here’s how to access an entire indexed array called ABC in Bash employing the syntax echo ${ABC[@]} and echo ${ABC[*]}:

#!/bin/bash

#Array creation
ABC=(Artcell Black CrypticFate)

#printing array length to the terminal using both expressions
echo "the array elements printed using \${ABC[@]}: ${ABC[@]}"
echo               # for adding extra spaces between the outputs
echo "the array elements printed using \${ABC[*]}: ${ABC[*]}"
EXPLANATION

In the above code, the expressions ${ABC[@]} and ${ABC[*]} expand the array to access the items and print them to the screen using the echo command.

accessing and printing elements
NOTE: The expressions above maintain a fundamental distinction though serving the same purpose. The syntax ${ABC[@]} expands each element as a separate word preserving the integrity of the individual elements. Contrarily, ${ABC[*]}  concatenates all the elements into a single word separated by a space. For example, with elements “apple”, “banana” “orange”, ${ABC[*]} treats them as a single string “apple banana orange”.

Access an Associative Array in Bash

To access the elements of an associative array in bash, use the same syntaxes echo ${assoc_array[@]} and echo ${assoc_array[*]}. However, it only prints the values associated with the keys. Here’s an example:

#!/bin/bash

#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"

#printing the array 
echo ${my_associative[@]}
EXPLANATION

Here, the ${my_associative[@]} expression accesses an associative array named my_associative with 3 key-value pairs. Finally, the command echo ${my_associative[@]} prints only the array values on the screen.

access bash associative array elements

NOTE: You can also access specific elements of the indexed array and associative array in Bash. To learn more, read the articles: Index Array in Bash and Bash Associative Arrays

Access the Last Array Element Using a Negative Index

Bash arrays can elegantly use the negative index to access the last element. Instead of counting from the start, negative indices count backward from the end of the array. For instance, -1 refers to the last element, -2 refers to the second last item, and so on. Thus, using the index assignment syntax with “-1”, ${your_array[-1]}, returns the last element and the echo command prints the value on the terminal.

To access the last element of an indexed array, you can use the syntax, echo ${your_array[-1]}, like the following example:

#!/bin/bash

# the array 
shoes=(adidas puma nike)

#print array
echo "all items: ${shoes[@]}"

echo 

# print last item
echo “last item:${shoes[-1]}
EXPLANATION

Here, the expression ${shoes[-1]} accesses the last element nike of the array shoes using the negative index ‘-1’ and the echo "last item:${shoes[-1]}" command prints the value nike on the screen.

access last element using negative index

Loop Through the Elements of Array in Bash

Using Bash loop-based methods are general approach to iterate over an array. To loop through the Bash array elements using for loop with the syntax for elem in ${array[@]}, see the example below:

#!/bin/bash

#Declaring an indexed array and assigning it with values 
fruit=(lichie pine orange)

#looping through the elements to print 
for item in ${fruit[@]}
    do
        echo $item
done 
EXPLANATION

First, the complete looping expression for elements in ${fruit[@]} iterates through the fruit array until it covers the entire array length (which is 3) and prints the items into the terminal iteratively on new lines using echo $item.

loop through the bash array elements

Add Array Elements

Adding a new element in an array is very simple in Bash. Use the =+ operator with the syntax array_name+=(element to add). By default, it adds an element to the end of the specified array.

Here’s an example to add an array element CSE in an indexed array named dept using syntax dept+=(CSE):

#!/bin/bash

#array declaration with elements 
dept=(EEE CE)

#print array before append
echo "before: ${dept[@]}"

#append element
dept+=(CSE)

#print array after append
echo "after adding new element: ${dept[@]}"
EXPLANATION
This script uses the syntax  dept+=(CSE) to add a new element CSE to the end of the dept array with 2 elements. The final echo command prints the array with 3 elements (EEE CE CSE).

adding new elements The snap above shows that the dept+=(CSE) expression adds a new element to the array dept which is evident after printing the array in the last line.

NOTE: To add multiple elements to an array, use array+=(item1 item2 ..ItemN). For instance, to add MME and ECE to the above array, the syntax is: dept+=(MME ECE)

Add Array Elements Using Index Assignment

The index assignment syntax array_name[index]=element adds a new element to an existing Bash array in any specified index.

I’ll use the same dept array to add 2 new elements Arch and CEE at index 2 and index 10 using the index assignment syntaxes dept[2]=Arch and dept[10]=CEE. Here’s how:

#!/bin/bash

#array declaration with elements 
dept=(EEE CE)

#print array before append
echo "before: ${dept[@]}"

#append element
dept[2]=Arch
dept[10]=CEE

#print array after append
echo "after adding new elements: ${dept[@]}"

#print index
echo "the indices are: ${!dept[@]}"
EXPLANATION
In this script, the dept[2]=Arch add a new element Arch to the dept array at the 3rd position. The dept[10]=CEE expression adds CEE to the array in the 4th position but with index number 10. The echo command prints the array and all the indices to verify the successful running of operations using echo "after adding new elements: ${dept[@]}" and echo "the indices are ${!dept[@]}"

adding elements of array using index assignmentHere, you can see that the assignment expression above adds 2 new elements (Arch CEE) to the dept array both in a contiguous manner (index 2) and in a random manner (index 10).

Modify Array Elements in Bash

To modify an array element is to replace the extant value with a new value in the same position. The syntax array[index]= new_valuemodifies the array element by updating with the new_value at the specified index. Here’s an example:

#!/bin/bash  
#Declaring the array  
hello=("i" "am" "kohli")  

#Printing all the elements of the Array  
echo "before:${hello[@]}"

#Updating the Array Element  
hello[2]=williamson  
  
#Printing all the elements of the Array  
echo "after modification:${hello[@]}"
EXPLANATION

Here, the hello[2]=williamson expression updates the content of index 2 (3rd position) from kohli to williamson. The echo "after modification:${hello[@]}" command prints the array with the updated contents.

modify the array valuesTerminal output to modify the array element from kohli to williamson.

Remove Array Elements

To delete an array element, use the unset command followed by the index value like the format: unset array_name[index]

Here’s an example to show how to remove an element from an indexed array:

#!/bin/bash

#create an indexed array
juice=("apple" "banana" "cherry" "date" "kiwi")

#print the entire array
echo ${juice[@]}

echo

#remove the element banana
unset juice[1]

#print array again
echo ${juice[@]}
EXPLANATION

In the script, the unset juice[1] command removes the 2nd element banana. After that, the echo command prints the array twice to show that the unset command has removed the array element.

removing array element using unset commandIn the above, the unset command removes the element banana from the array juice.

NOTE: To learn how to add, remove, and modify elements to a Bash associative array, read the article: “Bash Associative Arrays”

Extract a Particular Element from an Array in Bash

You can extract a specific part of an array element in Bash of string type. Take the array sen=(‘howdy parallel universe monster!’ ‘storm is coming’ ‘world cup ends’) for instance. If you want to extract words from the 1st element (‘howdy parallel universe monster!’), you can use modifiers in variable expansion like the below:

#!/bin/bash

#create the array
sen=('howdy parallel universe monster!' 'storm is coming' 'world cup ends')

#the array
echo "the array: ${sen[@]}"

# to get the first element
echo "1st element: ${sen[0]}"

#to get the last word “monster!”, remove prefix through the last space using ##*
echo "last word: ${sen[0]##* }"

#To get the first word, remove suffix starting with the first space using %% *
echo "1st word: ${sen[0]%% *}"

#The second word is harder; first remove through the first space
tmp="${sen[0]#* }"
#then get the first word of what remains
echo "2nd word: ${tmp%% *}"

# The third word (which might not be the last)? remove through the second space
tmp2="${sen[0]#* * }"
# ...then the first word again
echo "3rd word: ${tmp2%% *}"
EXPLANATION

Here, in the provided code:

${sen[0]##* }: Prints the last word of the first array element by removing everything before the last space.

${sen[0]%% *}: Prints the first word of the first array element by removing everything after the first space.

${sen[0]#* }: Extracts the words after the first space, and `${tmp%% *}` prints the first word from this extracted section.

${sen[0]#* * }: Extracts the words after the second space, and `${tmp2%% *}` prints the first word from this extracted section.

extract particular array elementThe above image states that the variable expansion has extracted elements (words) from the 1st array element (sentence).

Conclusion

In closing, this tutorial has discussed the intricacies of elements of arrays in Bash from accessing elements to manipulating them dynamically showing several hands-on illustrations. I hope this article empowers your scriptwriting capabilities in terms of efficient data handling and fosters elegant solution-building by mastering array fundamentals. Happy Scripting!

Frequently Asked Question

How to create a Bash array?

To create a Bash array:

  1. Use the syntax declare -a <array_name> to create an empty array.
  2. To create an array with initialized elements use: array_name=(element1 element2.. elementN).

How do you delete all the elements of an array in Bash?

Use the unset command followed by the array name to delete all the elements of an array in Bash. For example, to delete elements of an array named numbers, use: unset numbers.

OR,

You can recreate the same array using array_name=() or declare -a array_name. For instance, to delete all elements of the array numbers use the syntax: declare -a numbers=() or numbers=()

It is possible to access the Bash associative array elements using the negative index?

No, since Bash associative arrays don’t support negative indices to access elements. Rather, it uses a unique set of keys that are not maintained in any sequential order. A negative index is only an attribute available to the regular indexed arrays in Bash.

How to get the number of elements in the Bash array?

The number of elements of a Bash array is the length of that array. To get the length of an array in Bash, use the expression ${#your_array[@]) with the echo command. For instance, if you have an array nums=(1 2 3) which you intend to get the length of, then use the syntax echo ${#nums[@]}. It will return 3 as the output on the terminal.

What’s the syntax to access a specific element in a Bash array?

To access any specific element in a Bash array, use the syntax ${your_array[index]}, where index is the position of the element you want to access. For instance, the syntax echo ${number[0]} prints the first element of the array number.

How do I loop through all the elements in a Bash array?

To loop through all the elements in a Bash array use the Bash for loop syntax for elem in ${array[@]} to iterate over the entire array. For example, to iterate over the array number=(1 2 3 4), the syntax is:

for digit in ${number[@]}
    do
        echo $digit
done 

Output:

1

2

3

4

What is a Bash array?

A Bash array is a data structure that stores values in an indexed way. Unlike arrays in other programming languages, bash array can store different types of elements. For example, you can use Bash arrays to store both strings and numbers.

Related Articles


<< Go Back to Bash Array | Bash Scripting Tutorial

5/5 - (3 votes)
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment