Concatenating Arrays
You can concatenate two or more arrays using the +
operator:
fruits=(${fruits[@]} orange pear)
person=("${person[@]}" city=London)
In the first example, the orange
and pear
elements are added to the fruits
array. In the second example, the city=London
key-value pair is added to the person
associative array.
Merging Arrays
To merge the elements of two or more arrays into a single array, you can use the +
operator or the printf
command:
merged_array=(${fruits[@]} ${person[@]})
merged_array=($(printf '%s\n' "${fruits[@]}" "${person[@]}"))
Both of these examples will create a new array merged_array
that contains all the elements from the fruits
and person
arrays.
Sorting Arrays
You can sort the elements of an array using the sort
command:
sorted_fruits=($(echo "${fruits[@]}" | sort))
sorted_person=($(printf '%s\n' "${!person[@]}" | sort))
In the first example, the elements of the fruits
array are sorted and stored in the sorted_fruits
array. In the second example, the keys of the person
associative array are sorted and stored in the sorted_person
array.
You can perform various transformations on array elements, such as converting to uppercase or lowercase, using parameter expansion:
## Convert to uppercase
upper_fruits=("${fruits[@]^^}")
upper_person=("${!person[@]^^}" "${person[@]^^}")
## Convert to lowercase
lower_fruits=("${fruits[@],,[a-z]}")
lower_person=("${!person[@],,[a-z]}" "${person[@],,[a-z]}")
In the first two examples, the elements of the fruits
and person
arrays are converted to uppercase. In the last two examples, the elements are converted to lowercase.
Array Arithmetic
You can perform arithmetic operations on array elements using the $((expression))
syntax:
numbers=(1 2 3 4 5)
sum=$((${numbers[@]} + 10))
product=$((${numbers[@]} * 2))
In the above examples, the value of each element in the numbers
array is increased by 10 and multiplied by 2, respectively, and the results are stored in the sum
and product
variables.