What is Variable Array in Bash? [4 Cases]

The variable array is one of the essential features in Bash scripting. It is nothing but a data structure that provides a scheme for handling collections of data efficaciously. This variable array allows users to organize, manipulate and work with multiple values in an efficient manner. In this article, I’m going to share the insights of working with Bash variable array. So, let’s explore!

Key Takeaways

  • Learning about Bash variable array.
  • Learning how to manipulate variable arrays in Bash.

Free Downloads

What is Variable Array in Bash?

In Bash, a variable array refers to a single variable that holds multiple values as an array. Actually, arrays are zero-based, so the first element of the array is generally indexed with ‘0’. As there is no limited size of arrays, you can easily add or remove elements. Also, these variable arrays are so flexible that you can store different collections of elements in variables and manipulate them by your preference.

4 Cases for Variable Array Manipulation in Bash

Variable array manipulation is so common in Bash. You can add elements, remove elements, merge elements, and perform more operations on the arrays assigned to the Bash variables. Here, I am demonstrating 4 such cases of variable array manipulation in Bash:

Case 1: Sorting Arrays Alphabetically in Bash

To sort the elements of an array alphabetically, follow the mentioned steps below:

Steps to Follow >

➊ Open your Ubuntu Terminal.

➋ To open a script in the nano text editor, write the command below:

nano sort.sh
EXPLANATION
  • nano: A text editor.
  • sort.sh: This is a script. Here, I have named the script by ‘sort.sh’. You can name any of your choices.
Opening file in Nano text editor➌ Hereafter, write the following script inside the editor:

Script (sort.sh) >

#!/bin/bash

color=("red" "yellow" "blue" "green" "pink")

#Sorting array elements
sorted_color=($(printf '%s\n' "${color[@]}" | sort))

#Displaying the array
echo "${sorted_color[0]}"
echo "${sorted_color[1]}"
echo "${sorted_color[2]}"
echo "${sorted_color[3]}"
echo "${sorted_color[4]}"
EXPLANATION

In #!/bin/bash, ‘#!’ is known as ‘Shebang’ or ‘Hashbang’. The line color=(“red” “yellow” “blue” “green” “pink”) indicates an array named ‘color’ including five elements: “red”, “yellow”, “blue”, “green”, and “pink”. Then, sorted_color=($(printf ‘%s\n’ “${color[@]}” | sort)) takes the array elements of ‘color’ and sorts them alphabetically using the sort command. Here, ‘printf‘ prints each element of the ‘color’ array, and the sort command piping with ‘printf‘ sorts the elements.

➍ Then, press CTRL+S to save the file & press CTRL+X to exit.

➎ After that, use the command below to make the script executable:

chmod u+x sort.sh
EXPLANATION
  • chmod: Changes the permission of the files and directories.
  • u+x: Adds the executable permission for the user.
  • sort.sh: The file which you want to make executable.
Adding executable permission to the script➏ Finally, run the script by the following command:

./sort.sh

Showing the sorted array as outputFrom the image, you can see that the assigned array elements inside the ‘color’ variable have been sorted.

Case 2: Reversing Arrays Using Loop

You can use a loop to reverse the elements of a variable array. The following section depicts an example of traversing the elements of an array in reverse order.

You can follow the steps of Case 01, to save & make the script executable.

Script (reverse.sh) >

#!/bin/bash

color=("red" "blue" "green" "yellow")

#Reversing the array elements
reversed_color=()
for ((i=${#color[@]}-1; i>=0; i--)); do
    reversed_color+=("${color[i]}")
done

#Displaying the array
echo "${reversed_color[0]}"
echo "${reversed_color[1]}"
echo "${reversed_color[2]}"
echo "${reversed_color[3]}"
EXPLANATION
The line color=(“red” “blue” “green” “yellow”) indicates an array named ‘color’ including four elements: “red”, “blue”, “green”, and  “yellow”. The line ‘reversed_color=()’ initializes an empty array called ‘reversed_color’. Now, in ‘for ((i=${#color[@]}-1; i>=0; i–)); do’ the ‘for’ loop iterates over the array ‘color’ in reverse way. Here, ‘${#color[@]}-1’ specifies that the iteration starts with the last element of the array, and ‘i>=0; i–’ indicates that the loop decrements the index ‘i’ until it reaches 0.

In the line ‘reversed_color+=(“${color[i]}”)’ inside the loop, using the ‘+=’ operator, ‘${color[i]}’ accesses each element of the array ‘color’ at index ‘i’ and passes the value to the array ‘reversed_color’.

Now, run the script by the following command:

./reverse.sh

Showing the reversed array as outputFrom the above image, you can see that the output is showing the array elements in reverse order.

Case 3: Merging Arrays Using “+=” Operator

You can merge the separate values of different arrays using the ‘+=’ operator. Below is an example of merging different values of arrays:

You can follow the steps of Case 01, to save & make the script executable.

Script (merge.sh) >

#!/bin/bash

color=("Blue" "Brown")
cartoon=("Tom" "Jerry")

#Merging the two arrays
merged_array=()
for element in "${color[@]}" "${cartoon[@]}"; do
    merged_array+=("$element")
done

#Displaying the array
echo "${merged_array[0]}"
echo "${merged_array[1]}"
echo "${merged_array[2]}"
echo "${merged_array[3]}"
EXPLANATION
The lines ‘color=(“Blue” “Brown”)’, cartoon=(“Tom” “Jerry”) indicate two arrays named ‘color’ & ‘cartoon’. Now, the line ‘merged_array=()’ specifies an empty array ‘merged_array’ where the elements of ‘color’ & ‘cartoon’ will be stored.

In the line ‘for element in “${color[@]}” “${cartoon[@]}”; do’, the ‘for’ loop combines the arrays ‘color’ & ‘cartoon’ into one loop using the ‘“${color[@]}” “${cartoon[@]}”’ syntax and iterates over the elements of both arrays. Here, the variable ‘element’ holds each element of the arrays ‘color’ & ‘cartoon’. In ‘merged_array+=(“$element”)’, the ‘+=’ operator is used to append the ‘element’ to the ‘merged_array’.

Now, run the script by the following command:

./merge.sh

Showing the merged array elements as output in bashThe snapshot above depicts a merged array of the two assigned separated array elements.

Case 4: Removing Specific Elements From Any Array in Bash

You can remove particular elements from any variable array. Below is an example of such a case:

You can follow the steps of Case 01, to save & make the script executable.

Script (remove.sh) >

#!/bin/bash

color=("black" "orange" "red" "indigo")

#Removing an element from the array variable 'color'
unset color[1] #Remove 'orange' from the array

color=("${color[@]}") #Re-index the array 'color' to remove gaps

#Displaying the array
echo "${color[0]}" 
echo "${color[1]}" 
echo "${color[2]}"
EXPLANATION
Here, the line ‘color=(“black” “orange” “red” “indigo”)’ depicts an array ‘color’. ‘unset color[1]’ removes ‘orange’, the element at index 1 from the ‘color’ array. Then, the line ‘color=(“${color[@]}”)’ re-indexes the ‘color’ array to remove the internal gaps.

Now, run the script by the following command:

./remove.sh

The output of removing an element from the array in bashThe above screenshot displays that the desired element has been removed from the array.

Conclusion

The whole article symbolizes how you can work with Bash variable array for different cases. So, wrapping up, by utilizing the variable arrays properly, you can reduce the use of unnecessary individual variables and create more dynamic and organized Bash scripts.

People Also Ask

Can I create arrays with mixed data types in Bash?
Yes, you can create arrays with mixed data types. But Bash will consider all the elements including integers as strings.

Can I modify array elements after declaring the array?
Yes, you can modify array elements after declaring the array by accessing the elements using its index & assigning a new value to it.

What are indexed arrays in Bash?
The arrays assigned by integers in Bash are the indexed arrays.

Are indexed arrays 1 based in Bash?
No, Bash indexed arrays are zero-based. The indexes begin from 0 to n-1.

Can I pass arrays as arguments to the functions in Bash?
Yes, you can pass arrays as arguments to the functions in Bash.

How to echo an array in Bash?
To echo an array in Bash, use the syntax ‘echo “${variableArray_name[@]}”’.

Related Articles


<< Go Back to Types of Variables in Bash | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment