Skip to content

Instantly share code, notes, and snippets.

@thikade
Created September 30, 2019 06:20
Show Gist options
  • Save thikade/1f80c12c9e17588eeabc5111c9923b2d to your computer and use it in GitHub Desktop.
Save thikade/1f80c12c9e17588eeabc5111c9923b2d to your computer and use it in GitHub Desktop.
bash arrays cheatsheet

Docs

Bash Arrays

Declaration

Syntax Description
ARRAY=() Declares an indexed array ARRAY and initializes it to be empty. This can also be used to empty an existing array.
ARRAY[0]= Generally sets the first element of an indexed array. If no array ARRAY existed before, it is created.
declare -a ARRAY Declares an indexed array ARRAY. An existing array is not initialized.
declare -A ARRAY Declares an associative array ARRAY. This is the one and only way to create associative arrays.

Notes

  • numerical array indexes start at 0
  • Indexed arrays are always sparse, meaning indexes are not necessarily contiguous.

Storing values in INDEXED arrays

Syntax Description
ARRAY[N]=VALUE Sets the element N of the indexed array ARRAY to VALUE.
ARRAY=(E1 E2 …) Compound array assignment - sets the whole array ARRAY to the given list of elements indexed sequentially starting at zero. The array is unset before assignment unless the += operator is used. When the list is empty (ARRAY=()), the array will be set to an empty array. This method obviously does not use explicit indexes. An associative array can not be set like that! Clearing an associative array using ARRAY=() works.
ARRAY+=(E1 E2 …) Append to ARRAY.
ARRAY=("${ANOTHER_ARRAY[@]}") Copy ANOTHER_ARRAY to ARRAY, copying each element

Storing values in ASSOCIATIVE arrays

Syntax Description
ARRAY[STRING]=VALUE Sets the element indexed by STRING of the associative array ARRAY.
ARRAY=([S1]=E1 [S2]=E2 …) Individual mass-setting for associative arrays. The named indexes (here: S1 and S2) are strings

Accessing values

Syntax Description
${ARRAY[N]} Expands to the value of the index N in the indexed array ARRAY. If N is a negative number, it's treated as the offset from the maximum assigned index (can't be used for assignment) - 1

Metadata

Syntax Description
${#ARRAY[N]} Expands to the length of an individual array member at index N (stringlength)
${#ARRAY[STRING]} Expands to the length of an individual associative array member at index STRING (stringlength)
${#ARRAY[@]} ${#ARRAY[*]} Array Length; Expands to the number of elements in ARRAY
${!ARRAY[@]} ${!ARRAY[*]} KEYS; Expands to the indexes in ARRAY since BASH 3.0

Unsetting Arrays

Syntax Description
unset -v ARRAY Destroys a complete array
unset -v ARRAY[@] Same as above
unset -v ARRAY[*] Same as above
unset -v ARRAY[N] Destroys the array element at index N
unset -v ARRAY[STRING] Destroys the array element of the associative array at index STRING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment