Skip to content

Bash arrays API

Bash indexed arrays — one-dimensional, sparse, integer-indexed collections of strings.

1 class · 7 methods

arrays

7 methods

Bash indexed array operations: declaration, access, iteration and slicing.

arr=(a b c)

Declares an indexed array by assigning a list of values enclosed in parentheses.

Returns

array

Example

bash
fruits=("apple" "banana" "cherry")
echo ${fruits[1]}  # banana

# Append on declaration
nums=(1 2 3 4 5)
${arr[index]}

Returns the element at the given integer index (0-based).

Parameters

NameTypeDescription
indexintegerZero-based index.

Returns

string

Example

bash
arr=("a" "b" "c")
echo ${arr[0]}  # a
echo ${arr[2]}  # c
arr[5]="z"       # sparse: index 3,4 are empty
${arr[@]}

Expands to all elements of the array as separate quoted words. Use [*] for a single word.

Returns

string list

Example

bash
arr=("a" "b" "c")
echo ${arr[@]}   # a b c
for x in "${arr[@]}"; do
    echo "x=$x"
done
${#arr[@]}

Returns the number of assigned elements in the array (not the highest index).

Returns

integer

Example

bash
arr=("a" "b" "c")
echo ${#arr[@]}  # 3

arr[10]="z"
echo ${#arr[@]}  # 4 (sparse array)
arr+=(d e)

Appends one or more elements to the end of an existing indexed array.

Parameters

NameTypeDescription
elementsstringValues to append.

Returns

array

Example

bash
arr=("a" "b")
arr+=("c" "d")
echo ${arr[@]}  # a b c d
unset arr[index]

Removes the element at the given index. The array becomes sparse; indices are not shifted.

Parameters

NameTypeDescription
indexintegerIndex of element to remove.

Returns

void

Example

bash
arr=("a" "b" "c")
unset arr[1]
echo ${arr[@]}    # a c
echo ${arr[1]}    # (empty)
${arr[@]:start:count}

Returns a slice of count elements starting at index start.

Parameters

NameTypeDescription
startintegerStart index.
countintegerNumber of elements.

Returns

string list

Example

bash
arr=(1 2 3 4 5)
echo ${arr[@]:1:3}  # 2 3 4
echo ${arr[@]:2}    # 3 4 5 (to end)