Arrays
| Since: | Bash(bash拡張) |
|---|
In shell scripts, bash supports both regular arrays (indexed arrays) and associative arrays (key-value pairs). Arrays are useful when you want to process multiple values together, such as a list of files or command arguments. Associative arrays require a declare -A declaration and are a bash 4.0+ feature.
Declaring and Assigning Indexed Arrays
Regular arrays can be declared all at once using (), or elements can be assigned individually by specifying an index. Indices start at 0.
| Syntax | Description |
|---|---|
arr=(a b c) | Declares an array by listing elements separated by spaces. Indices are automatically assigned starting from 0. |
arr[0]=a | Assigns value a to index 0. Any index can be assigned individually. |
arr+=( d e ) | Appends elements to the end of an existing array. |
declare -a arr | Explicitly declares a variable as an indexed array. Can be combined with an assignment. |
Accessing and Manipulating Indexed Arrays
To access an element, write ${arr[n]}. To expand all elements, use ${arr[@]}.
| Syntax | Description |
|---|---|
${arr[0]} | Gets the element at index 0. |
${arr[@]} | Expands all elements as separate strings. Used in for loops and when passing arguments. Wrapping in double quotes preserves spaces within elements. |
${arr[*]} | Expands all elements as a single string joined by the first character of IFS (a space by default). |
${#arr[@]} | Returns the number of elements (length) in the array. |
${!arr[@]} | Returns all indices (subscripts) of the array. Useful when indices are not contiguous. |
unset arr[n] | Deletes the element at index n. Other elements' indices are not compacted. |
unset arr | Deletes the entire array. |
${arr[@]:s:n} | Extracts n elements starting from index s (slice). |
Associative Arrays (declare -A)
To use an associative array, it must first be declared with declare -A. Keys are strings, allowing meaningful names instead of numeric indices. Requires bash 4.0 or later.
| Syntax | Description |
|---|---|
declare -A map | Declares variable map as an associative array. Always declare first, as assigning before declaration creates a regular variable. |
map[key]=value | Assigns value to key key. |
declare -A map=([k1]=v1 [k2]=v2) | Declares and initializes keys and values at the same time. |
${map[key]} | Gets the value for key key. |
${map[@]} | Expands all values. Order is not guaranteed. |
${!map[@]} | Expands all keys. |
${#map[@]} | Returns the number of elements in the associative array. |
unset map[key] | Deletes the element with key key. |
Iterating with Loops
To process all elements of an array, use for ... in "${arr[@]}". To iterate over an associative array as key-value pairs, extract keys with ${!map[@]} and access values with ${map[$key]}.
| Pattern | Description |
|---|---|
for item in "${arr[@]}"; do ... done | Iterates over each element of an indexed array. Without double quotes, elements containing spaces will be split. |
for i in "${!arr[@]}"; do ... done | Iterates over indices. Access values with ${arr[$i]}. |
for key in "${!map[@]}"; do ... done | Iterates over all keys of an associative array. Access corresponding values with ${map[$key]}. |
Sample Code
dragonball_array.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates indexed array declaration,
# manipulation, and loops using Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# 1. Array declaration (all at once)
# -----------------------------------------------
# Elements listed with spaces inside () are assigned indices starting from 0
fighters=("Goku" "Vegeta" "Piccolo" "Krillin" "Trunks")
echo "=== Indexed array: fighters ==="
# Access a specific index
echo "fighters[0]: ${fighters[0]}" # Goku
echo "fighters[2]: ${fighters[2]}" # Piccolo
echo ""
# -----------------------------------------------
# 2. Expanding all elements and getting the count
# -----------------------------------------------
# Expand all elements with ${fighters[@]}
echo "All fighters: ${fighters[@]}"
# Get the number of elements with ${#fighters[@]}
echo "Number of fighters: ${#fighters[@]}"
echo ""
# -----------------------------------------------
# 3. Process all elements with a for loop
# -----------------------------------------------
echo "=== Participating fighters ==="
for name in "${fighters[@]}"; do
echo " - ${name}"
done
echo ""
# -----------------------------------------------
# 4. Loop with index
# -----------------------------------------------
echo "=== Indexed list ==="
for i in "${!fighters[@]}"; do
echo " [${i}] ${fighters[$i]}"
done
echo ""
# -----------------------------------------------
# 5. Adding and removing elements
# -----------------------------------------------
# Append an element to the end with +=
fighters+=("Gohan")
echo "Element count after adding: ${#fighters[@]}"
# Delete a specific index with unset (indices are not compacted)
unset fighters[1] # Remove Vegeta
echo "All elements after deletion: ${fighters[@]}"
# Check remaining indices with ${!fighters[@]}
echo "Remaining indices: ${!fighters[@]}"
echo ""
# -----------------------------------------------
# 6. Slicing
# -----------------------------------------------
# Extract 2 elements starting from index 2
echo "Slice [2:2]: ${fighters[@]:2:2}"
chmod +x dragonball_array.sh ./dragonball_array.sh === Indexed array: fighters === fighters[0]: Goku fighters[2]: Piccolo All fighters: Goku Vegeta Piccolo Krillin Trunks Number of fighters: 5 === Participating fighters === - Goku - Vegeta - Piccolo - Krillin - Trunks === Indexed list === [0] Goku [1] Vegeta [2] Piccolo [3] Krillin [4] Trunks Element count after adding: 6 All elements after deletion: Goku Piccolo Krillin Trunks Gohan Remaining indices: 0 2 3 4 5 Slice [2:2]: Piccolo Krillin
dragonball_assoc.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates associative array declaration,
# access, and loops using Dragon Ball characters
# Requires bash 4.0 or later
# -----------------------------------------------
# -----------------------------------------------
# 1. Associative array declaration (declare -A is required)
# -----------------------------------------------
declare -A power_level
# Assign keys and values individually
power_level["Goku"]=9000
power_level["Vegeta"]=8000
power_level["Piccolo"]=3500
power_level["Krillin"]=1500
power_level["Trunks"]=5000
echo "=== Associative array: power_level ==="
# Access a value by specifying its key
echo "Goku's power level: ${power_level["Goku"]}"
echo "Piccolo's power level: ${power_level["Piccolo"]}"
echo ""
# -----------------------------------------------
# 2. Element count and expanding all values and keys
# -----------------------------------------------
echo "Number of registered fighters: ${#power_level[@]}"
# Expand all keys with ${!map[@]}
echo "Keys: ${!power_level[@]}"
# Expand all values with ${map[@]}
echo "Power levels: ${power_level[@]}"
echo ""
# -----------------------------------------------
# 3. Loop over key-value pairs
# -----------------------------------------------
echo "=== Power Level Rankings ==="
for chara in "${!power_level[@]}"; do
echo " ${chara}: ${power_level[$chara]}"
done
echo ""
# -----------------------------------------------
# 4. Updating and deleting elements
# -----------------------------------------------
# Reassigning to an existing key overwrites the value
power_level["Goku"]=150000000
echo "Super Saiyan awakened: Goku's power -> ${power_level["Goku"]}"
# Delete a key with unset
unset power_level["Krillin"]
echo "Element count after removing Krillin: ${#power_level[@]}"
echo ""
# -----------------------------------------------
# 5. Checking if a key exists
# -----------------------------------------------
# Use ${map[$key]+x} to check if a key exists (expands to "x" if it exists)
check_key="Vegeta"
if [[ -n "${power_level[$check_key]+x}" ]]; then
echo "${check_key} is in the list (power level: ${power_level[$check_key]})"
else
echo "${check_key} is not in the list"
fi
chmod +x dragonball_assoc.sh ./dragonball_assoc.sh === Associative array: power_level === Goku's power level: 9000 Piccolo's power level: 3500 Number of registered fighters: 5 Keys: Goku Vegeta Piccolo Krillin Trunks Power levels: 9000 8000 3500 1500 5000 === Power Level Rankings === Goku: 9000 Vegeta: 8000 Piccolo: 3500 Krillin: 1500 Trunks: 5000 Super Saiyan awakened: Goku's power -> 150000000 Element count after removing Krillin: 4 Vegeta is in the list (power level: 8000)
Difference Between ${arr[@]} and ${arr[*]}
| Syntax | With double quotes | Without double quotes |
|---|---|---|
${arr[@]} | Expands each element as a separate argument. Spaces within elements are preserved. "${arr[@]}" is recommended for for loops and passing arguments to functions. | Word splitting occurs; elements containing spaces are split. |
${arr[*]} | Expands all elements as a single string joined by the first character of IFS (a space by default). Useful for CSV output. | Same word-splitting behavior as unquoted "${arr[@]}". |
Notes
Indexed arrays in shell scripts are declared with arr=(a b c) and elements are accessed with ${arr[n]}. Use "${arr[@]}" to expand all elements, ${#arr[@]} to get the element count, and ${!arr[@]} to get all indices. In a for name in "${arr[@]}" loop, always include the double quotes to prevent elements containing spaces from being incorrectly split. Associative arrays are declared with declare -A map and elements are assigned with map[key]=value. Use ${!map[@]} to extract all keys and ${map[@]} to extract all values. The ${map[$key]+x} pattern is convenient for checking if a key exists. See also Variable Basics.
If you find any errors or copyright issues, please contact us.