arrays
7 methodsBash 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
| Name | Type | Description |
|---|---|---|
| index | integer | Zero-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
| Name | Type | Description |
|---|---|---|
| elements | string | Values to append. |
Returns
array
Example
bash
arr=("a" "b")
arr+=("c" "d")
echo ${arr[@]} # a b c dunset arr[index]Removes the element at the given index. The array becomes sparse; indices are not shifted.
Parameters
| Name | Type | Description |
|---|---|---|
| index | integer | Index 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
| Name | Type | Description |
|---|---|---|
| start | integer | Start index. |
| count | integer | Number 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)