Master Bash Arrays: Define, Access, Loop, and Manipulate Efficiently
This guide explains how to define, initialize, access, iterate, and modify Bash arrays, providing clear code examples and a practical case for checking installed packages, helping you write more efficient and readable shell scripts.
In Unix/Linux programming, Bash scripts are powerful for automation, and arrays are a fundamental data structure that can be used flexibly.
Defining and Initializing Arrays
Arrays can be created without explicit type declarations by assigning space‑separated values; quotes are required for elements containing spaces.
# Create an array with multiple elements
build_dependencies=(isomd5sum createrepo createrepo_c genisoimage rpm-build rpmdevtools) my_array=("element 1" "element 2" "element 3")Accessing Array Elements
Elements are accessed by zero‑based index using ${array[index]}. Example:
echo ${build_dependencies[0]} # outputs isomd5sumThe length of an array is obtained with ${#array[@]}, which is useful for loops.
Iterating Over Arrays
Bash offers several ways to loop through arrays:
Standard for loop
for i in "${my_array[@]}"; do
echo $i
doneIndex‑based loop
for index in "${!my_array[@]}"; do
echo "${my_array[$index]}"
doneC‑style for loop
for ((i=0; i<${#my_array[@]}; i++)); do
echo "${my_array[i]}"
doneAdding and Removing Elements
To append elements, use the += operator: my_array+=("new element") To delete an element, use unset with the index:
unset my_array[2]Practical Example
The following script checks whether a list of packages is installed on a Linux system:
#!/bin/bash
packages=(nginx apache2 mysql)
for pkg in "${packages[@]}"; do
if dpkg -l | grep -q $pkg; then
echo "$pkg is installed."
else
echo "$pkg is not installed."
fi
doneConclusion
Bash arrays provide a flexible and powerful way to organize and manipulate data in shell scripts. Mastering array operations greatly improves script efficiency and readability, making them indispensable for both simple lists and complex data handling.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
