Arrays are versatile and indispensable tools in shell scripting, allowing you to store, manage, and manipulate multiple values efficiently. In this comprehensive guide, we will delve into the world of arrays in shell scripts. Our goal is to equip you with the knowledge and skills to create, manipulate, and utilize arrays effectively. We will provide step-by-step examples and real-world outputs to help you master this essential scripting technique.
Introduction to Arrays in Shell Scripts
Arrays are data structures that can hold multiple values under a single variable name. They are particularly useful when you need to work with lists of items, such as filenames, user input, or numerical data.
Declaring and Initializing Arrays
To create an array in a shell script, you can declare it using the declare
keyword or by directly assigning values to it. Here’s how you can declare and initialize an array:
# Declare an array using 'declare'
declare -a my_array
# Initialize the array with values
my_array=("apple" "banana" "cherry" "date")
Alternatively, you can declare and initialize an array in a single line:
my_array=("apple" "banana" "cherry" "date")
Accessing Array Elements
You can access individual elements of an array using their index. Remember that array indices in shell scripts start at 0. Here’s how you can access array elements:
# Access the first element
first_element="${my_array[0]}"
# Access the second element
second_element="${my_array[1]}"
Modifying Array Elements
Arrays are mutable, which means you can change their elements after initialization. Here’s how you can modify array elements:
# Change the value of the third element
my_array[2]="grape"
# Append a new element to the end of the array
my_array+=("fig")
Iterating Through Arrays
You can use loops, such as for
or while
, to iterate through the elements of an array. Here’s an example using a for
loop:
# Iterate through the elements of the array
for fruit in "${my_array[@]}"; do
echo "Fruit: $fruit"
done
Array Length
To determine the length of an array (i.e., the number of elements it contains), you can use the ${#array[@]}
syntax:
# Get the length of the array
array_length="${#my_array[@]}"
echo "Array length: $array_length"
Example: Storing and Printing File Names
Let’s walk through a practical example where we use an array to store and print filenames in a directory:
# Declare an empty array
file_names=()
# Populate the array with filenames in the current directory
for file in *; do
if [ -f "$file" ]; then
file_names+=("$file")
fi
done
# Print the filenames
echo "List of files in the current directory:"
for name in "${file_names[@]}"; do
echo "$name"
done