Advanced Use of Arrays in Shell Scripts
If any coder does not worship the arrays, it is probably not a good one. :) Bash is a shell programming language, so you need arrays while coding Bash. In this article, I’ll briefly introduce array logic in bash scripts. We will consider one-dimensional indexed arrays and associative arrays (key, value pairs).
In math, an array refers to a set of numbers or objects that will follow a specific pattern. An array is an orderly arrangement (often in rows, columns, or a matrix) that is most commonly used as a visual tool for demonstrating multiplication and division. The arrays are used to enter a large amount of data into the computer, process it quickly, and store it appropriately.
Is an array in programming analogous to a matrix in mathematics? Yes, especially when you allow for two-dimensional arrays. There are two types of bash arrays:
- Indexed arrays: the array is referred to via integers or numbers.
- Associative arrays: the array is referred to via strings or a set of characters and words.
The other advanced languages have extra multidimensional arrays. But remember that bash does not support multidimensional arrays, so it’s not possible to add an array within an array.
Indexed Array
There are a few ways to declare indexed arrays in Bash. Meanwhile, it’s worth knowing that array size does not need to be declared and starts at 0 (zero).
arr=() #arr is an empty array.
This creates an empty array command.
arr=("Batur" "Orkun" "DevOps")
arr=([0]="Batur" [1]="Orkun" [2]="DevOps")
This is creating a filled-with-data array command. Suit yourself, you can use indices or not.
arr=([1]="Batur" [0]="Orkun" [4]="DevOps")
Following index numbers in order is unnecessary, and you can pass some indices like the above.
echo ${arr[0]} # Output: Orkun
If you want to change values, you can do so as below.
arr[0]="New Surname"
If you want to print all values, you need the “@” character. Notice that indices are important, not order.
arr=([1]="Batur" [0]="Orkun" [4]="DevOps")
echo ${arr[@]}. # Output: Orkun Batur DevOps
If you love to stick to the rules, use the “declare” statement to define your array. But it is not compulsory.
declare -a Arr
Arr=("Batur" "Orkun" "DevOps")
Let’s do a for-loop example.
#!/usr/bin/env bash
declare -a Arr=("Batur" "Orkun" "DevOPS")
for item in ${Arr[@]}; do
echo "> $item"
done
### Output:
# > Batur
# > Orkun
# > DevOPS
If you want to add a new item to the array, use the “+=” operator.
declare -a Arr=("Batur" "Orkun" "DevOPS")
Arr+=("Hello")
for item in ${Arr[@]}; do
echo "> $item"
done
### Output:
# > Batur
# > Orkun
# > DevOPS
# > HEYYY
Associative Array
While indexed arrays don’t require the declaration ( “declare” ), associative arrays do.
declare -A AssocArr
declare -A AssocArr=( [name]="batur" [surname]="Orkun" [title]="DevOps" )
You should never use the “@” character to print all, because the order may be different. For example, my output was “Orkun DevOPS batur” for the array above.
If you want to change values:
AssocArr[name]="BATUR"
If you want to add a new item to the array, use the “+=” operator.
AssocArr+=([os]="Linux")
Multiples are possible.
AssocArr+=([os]="Linux" [skill]="Kubernetes")
If you want to remove an item from the array, use the unset” command.
unset AssocArr[name]
You can use loops with arrays as well.
declare -A AssocArr=([name]="batur" [surname]="Orkun" [title]="DevOPS")
AssocArr+=([os]="Linux")
AssocArr+=([os]="Linux" [skill]="Kubernetes")
for key in ${!AssocArr[@]}; do
echo "$key : ${AssocArr[$key]}"
done
### Output:
# surname : Orkun
# title : DevOPS
# skill : Kubernetes
# os : Linux
# name : batur
Extra Usages
Arrays are often a perfect data structure for creating and manipulating.
A script that detects files and directories in the current directory and writes it to the screen.
list=( $(ls) )
for item in ${list[@]}; do
if [ -d "../$item" ]; then
echo "Directory $item"
else
echo "File $item"
fi
done
To extract a chunk of an array, you can use a syntax that:
${Arr[1]:s:n}
This syntax will return a slice of the array beginning at position “s” and containing “n” items. You can omit the “:n” part to extract all items from s until the end of the list.
declare -a Arr=("Batur" "Orkun" "DevOPS")
echo ${Arr[1]:1:3}
### Output:
# rku
To search and replace in an array of elements, you can use a syntax that:
${Arr[1]/find/replace}
This syntax is a regex actually (Regular Expression). Find the first keyword and replace it with the second keyword.
declare -a Arr=("Batur" "Orkun" "DevOPS")
echo ${Arr[1]/kun/-KUN}
### Output:
# Or-KUN
Conclusion
Arrays in Bash may have limitations, but they offer the same basic functionality as most programming languages do. It is important to use the latest Bash version. For example, there was no support for associative arrays before version 4. However, Bash is everywhere and is a strong programming language. So you can use it everywhere. Knowing Bash is an important skill, whether you’re a developer or in DevOps.