KandZ – Tuts

We like to help…!

Linux CLI 70 🐧 Arrays in shell scripts

a - Arrays in shells scripts Part 1
arrays are used to store multiple values under a single variable name
Arrays are zero-indexed and declared with ()
Use quotes to preserve spaces and avoid word splitting.
Use ${array[@]} in loops for correct iteration.
Associative arrays (with declare -A) allow key-value mapping.
Bash does not support native multi-dimensional arrays, but can simulate them.
Declaring Arrays → Arrays in Bash are declared using parentheses and space-separated values
my_array=(value1 value2 value3)
my_array=() → declares an empty array
my_array=("value with space" "another value") → declares an array with values and quoting elements with spaces

b - Arrays in shells scripts Part 2
Accessing Array Elements → Access elements using ${array[index]}:
echo ${my_array[0]} → Accessing Array Element 0
echo ${my_array[index]} → Accessing Array Element using a variable as the index
Iterating Over Arrays → Use a for loop to process each element
for element in "${my_array[@]}"; do → iterates over my_array
Use quotes around ${my_array[@]} to preserve spaces and prevent word splitting.
${my_array[*]} vs ${my_array[@]}
${my_array[*]} joins elements into a single string (useful for passing to commands).
${my_array[@]} expands each element as a separate word.

c - Arrays in shells scripts Part 3
Appending elements
my_array+=("new element")
Assigning specific indices
my_array[3]="fourth element"
Array Length
echo ${#my_array[@]} → gets number of elements
echo ${#my_array} → get the size of the element
Slicing Arrays → Use ${array[@]:offset:number} to extract a subset:
echo "${my_array[@]:1:2}" → slices an array
Check if array is empty
if [ ${#my_array[@]} -eq 0 ]; then
Associative Arrays
my_assoc_array["key1"]="value1"

Leave a Reply