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"
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!