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:
➊ Open your Ubuntu Terminal.
➋ To open a script in the nano text editor, write the command below:
nano sort.sh
- 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.
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]}"
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
- 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.
./sort.sh
From 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.
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]}"
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
From 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:
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]}"
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
The 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:
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]}"
Now, run the script by the following command:
./remove.sh
The 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
Related Articles
- What Are Built-in Variables in Bash [2 Cases With Examples]
- An Ultimate Guide of Using Bash Environment Variables
- The “.bashrc” Environment Variables [4 Cases]
- String Variables in Bash [Manipulation, Interpolation & Testing]
- An Extensive Exploration of Bash Special Variables [9 Examples]
- What is Boolean Variable in Bash? [3 Cases With Examples]
- What is HereDoc Variable in Bash? [5 Practical Cases]
- What is PS1 Variable in Bash? [3 Customization Examples]
- What is PS3 Variable in Bash? [3 Practical Examples]
<< Go Back to Types of Variables in Bash | Bash Variables | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners