0
0
Bash Scriptingscripting~5 mins

Why arrays handle lists of data in Bash Scripting

Choose your learning style9 modes available
Introduction
Arrays let you keep many pieces of related information together in one place. This helps you organize and work with lists of data easily.
You want to store a list of filenames to process one by one.
You need to keep track of multiple user inputs in a script.
You want to save a list of server IP addresses to connect to.
You have a set of options or choices to check in your script.
You want to loop through a list of items to perform the same action.
Syntax
Bash Scripting
declare -a array_name
array_name=(item1 item2 item3 ...)
# Access item: ${array_name[index]}
# Get all items: ${array_name[@]}
Arrays start with index 0, so the first item is at index 0.
Use ${array_name[@]} to get all items in the array.
Examples
Stores three fruits and prints the first one: apple.
Bash Scripting
declare -a fruits
fruits=(apple banana cherry)
echo ${fruits[0]}
Shows what happens with an empty array (prints nothing).
Bash Scripting
declare -a empty_array
# This array has no items yet
echo ${empty_array[@]}
Array with one item prints that item.
Bash Scripting
declare -a single_item
single_item=(onlyone)
echo ${single_item[0]}
Prints the last item in the array: blue.
Bash Scripting
declare -a colors
colors=(red green blue)
echo ${colors[2]}
Sample Program
This script shows how to create an array, add an item, and access items by index.
Bash Scripting
#!/bin/bash

# Create an array of animals
declare -a animals
animals=(dog cat bird)

# Print all animals before adding
echo "Animals before adding: ${animals[@]}"

# Add a new animal
animals+=(fish)

# Print all animals after adding
echo "Animals after adding: ${animals[@]}"

# Print the first animal
echo "First animal: ${animals[0]}"

# Print the last animal
last_index=$((${#animals[@]} - 1))
echo "Last animal: ${animals[$last_index]}"
OutputSuccess
Important Notes
Accessing an index that does not exist returns an empty string.
Adding items with += appends to the array without overwriting.
Arrays are useful when you want to group related data and loop through it.
Summary
Arrays store multiple related items in one variable.
You can access items by their position using indexes.
Arrays help organize and process lists of data easily in scripts.