Description
In Bash, an array is a collection of elements that act as variables. They have a ton of uses and this article will go over some of the basics when it comes to using arrays and elements in your Bash scripts.
Defining an Array
Array of string values
array=("pineapple" "blueberry" "mango" "kiwi" "dragonfruit")
Array of integers
integers=(2 9 3 11 8)
Calling an Array
Call an entire array
echo "I enjoy eating ${array[@]}"
Result: I enjoy eating pineapple blueberry mango kiwi dragonfruit
Call a specific array element
Example 1
echo "I enjoy eating ${array[3]}"
Result: I enjoy eating kiwi
Example 2
echo "I enjoy eating ${array[0]}"
Result: I enjoy eating pineapple
Array Iteration
Iterate through an array using a for loop
for fruit in ${array[@]}; do
echo "I enjoy eating $fruit"
done
Result:
I enjoy eating pineapple
I enjoy eating blueberry
I enjoy eating mango
I enjoy eating kiwi
I enjoy eating dragonfruit
Counting Array Elements
echo "There are ${#array[@]} elements in the array"
Result: There are 5 elements in the array
Sorting Array Elements
# Define an array of integers
integers=(2 9 3 11 8)
#Sort array
sorted_numbers=($(echo "${integers[@]}" | tr ' ' '\n' | sort -n))
#Print the result
echo ${sorted_numbers[@]}
Result: 2 3 8 9 11
Concatenating Arrays
# Define two arrays of strings
colors=("red" "green" "blue")
more_colors=("orange" "purple")
# Concatenate the two arrays
combined=("${colors[@]}" "${more_colors[@]}")
# Print the result
echo "Combined colors: ${combined[@]}"
Result: Combined colors: red green blue orange purple
Slice an Array
# Define an array of integers
integers=(2 9 3 11 8)
# Slice the array to create a new array with elements 3 through 7
sliced_integers=("${integers[@]:2:5}")
# Print the result
echo "Sliced integers: ${sliced_integers[@]}"
Result: Sliced integers: 3 11 8
Leave a Reply