Bash Array Basics
Arrays are fundamental data structures in Bash that allow storing multiple values under a single variable name. Understanding bash array declaration and initialization is crucial for effective shell scripting.
Array Declaration and Types
Bash supports two primary array types: indexed arrays and associative arrays. Here's a comprehensive overview:
Array Type |
Declaration Method |
Key Characteristics |
Indexed Array |
Numeric indices starting from 0 |
Ordered sequence of elements |
Associative Array |
String-based keys |
Key-value pair storage |
Indexed Array Examples
## Method 1: Declare and initialize in one line
fruits=("apple" "banana" "cherry")
## Method 2: Declare and add elements individually
colors=()
colors[0]="red"
colors[1]="green"
colors[2]="blue"
Associative Array Examples
## Declare associative array
declare -A person=(
["name"]="John Doe"
["age"]=30
["city"]="New York"
)
Array Initialization Techniques
Bash provides multiple ways to initialize arrays:
flowchart LR
A[Array Initialization] --> B[Direct Assignment]
A --> C[Read from Input]
A --> D[Command Substitution]
A --> E[Range Generation]
Practical Initialization Methods
## Command substitution
log_files=($(ls *.log))
## Range generation
numbers=($(seq 1 10))
## Dynamic input
read -a user_input
When working with bash array declaration, consider:
- Memory usage increases with array size
- Large arrays can impact script performance
- Use appropriate initialization techniques
By mastering these bash array types and initialization techniques, developers can efficiently manage and manipulate data in shell scripting environments.