Introduction
In programming, you often need to store a list of related items—like filenames, user IDs, or server names. Instead of creating a separate variable for each item (e.g., file1, file2, file3), you can use a single variable called an Array.
An array allows you to store multiple values under one name. You can think of it as a list where you can add, remove, and read items.
Arrays become useful as soon as one variable is no longer enough. Server lists, filenames, package names, and user accounts are all examples of data that naturally comes in groups rather than one value at a time.
In this lab, you will learn how to:
- Declare an array with an initial set of values.
- Append new items to the array.
- Print all elements in the array.
- Iterate (loop) through the array to process each item individually.
Declare an Array
Let's start by creating a script that holds a list of names.
Arrays are the shell's way of treating related values as a group instead of scattering them across many separate variables. This is useful whenever your script needs to process a collection rather than a single item.
Create the script array_lab.sh:
cd ~/project
nano array_lab.sh
Type this code to initialize an array:
#!/bin/bash
## Define an array named 'names'
names=("Alice" "Bob")
Syntax Rules:
- Use parentheses
()to enclose the list of values. - Use spaces (not commas) to separate the items.
("Alice" "Bob")is correct.("Alice", "Bob")is incorrect because the comma would be treated as part of the string "Alice,".
That last point reflects a broader shell rule: Bash syntax often looks simple, but small punctuation differences change meaning. Arrays are whitespace-separated lists, not comma-separated lists as in some other languages.
Save (Ctrl+O) and Exit (Ctrl+X).
Check your file content:
cat array_lab.sh
You have successfully defined an array variable, although the script doesn't produce any output yet.
Add an Element to the Array
Often, you won't know all the items in your list when you start. You may need to add items dynamically as your script runs.
This is common in real scripts. You might build an array of matching files, active hosts, failed services, or package names discovered during execution.
We can add (append) a new item to the end of an array using the += operator.
Open the script:
nano array_lab.sh
Add the following line at the bottom:
## Append 'Charlie' to the list
names+=("Charlie")
Explanation:
+=means "append to the existing value".("Charlie")wraps the new item in parentheses to ensure it is treated as an array element.
Your file should now look like this:
#!/bin/bash
## Define an array named 'names'
names=("Alice" "Bob")
## Append 'Charlie' to the list
names+=("Charlie")
Save and Exit.
Print All Elements
To verify that our array contains everything we expect, we can print all its elements at once.
In Bash, accessing an array variable is slightly different from a normal variable. You use ${array_name[@]} to expand all elements.
@is a special symbol acting as a wildcard for "all elements".
The ${...} form is another example of parameter expansion. Bash is not just printing the variable name literally; it is expanding the array into its stored elements before echo sees the final text.
Open array_lab.sh:
nano array_lab.sh
Add the print command:
## Print all elements in the array
echo "All Names: ${names[@]}"
Save and Exit.
Make the script executable and run it:
chmod +x array_lab.sh
./array_lab.sh
Result:
All Names: Alice Bob Charlie
The syntax ${names[@]} expanded into a space-separated list of all items in the array.
Iterate Through the Array
Printing the whole list is useful for debugging, but usually, you want to process each item individually. For example, you might want to create a user account for each name in the list.
To do this, we use a for loop.
Open array_lab.sh:
nano array_lab.sh
Add the loop at the end:
echo "--- Processing Names ---"
## Loop through each item in the array
for name in "${names[@]}"; do
echo "Hello, $name"
done
Your full script should now look like this:
#!/bin/bash
names=("Alice" "Bob")
names+=("Charlie")
echo "All Names: ${names[@]}"
echo "--- Processing Names ---"
for name in "${names[@]}"; do
echo "Hello, $name"
done
Save and Exit. Run it:
./array_lab.sh
Result:
Quoting "${names[@]}" is also important. It preserves each array element as its own item, which matters when values contain spaces. That detail becomes more important in real-world scripts where filenames and arguments are not always simple one-word strings.
All Names: Alice Bob Charlie
--- Processing Names ---
Hello, Alice
Hello, Bob
Hello, Charlie
The loop took each name from the array, assigned it to the variable name, and ran the code block. This is the most common way to handle lists in Bash.
Summary
In this lab, you have learned the fundamentals of using arrays in Bash:
- Declaration (
name=(...)): Creating a list with initial values. - Appending (
+=): Adding new items to an existing array dynamically. - Expansion (
${name[@]}): Retrieving all items in the array. - Iteration (
for): Processing each item in the list one by one.
Arrays are essential for writing scripts that need to handle multiple files, users, or data points efficiently.



