Skip to content

Instantly share code, notes, and snippets.

@gulhe
Last active April 30, 2024 12:44
Show Gist options
  • Save gulhe/550592d88b9030c588a85db099f99c0d to your computer and use it in GitHub Desktop.
Save gulhe/550592d88b9030c588a85db099f99c0d to your computer and use it in GitHub Desktop.
Bash Arrays Cheat Sheet

Bash Arrays

Declaration

๐Ÿ“ Array

#optional
declare -a array

๐Ÿ—‚๏ธ Associative Array

#mandatory
declare -A assocArray

Important

Note the distinction between "-a" for array and "-A" for Associative arrays

Affectation

Whole

๐Ÿ“ Array

array=(elem1 elem2 elem3)

๐Ÿ—‚๏ธ Associative Array

assocArray=([key1]=value1 [key2]=value2 [key3]=value3)

Tip

Don't hesitate to make use of "double quotes" if you need trickier values or keys

Push

Note

The syntax is very similar to whole array affectation

๐Ÿ“ Array

array+=elemN

๐Ÿ—‚๏ธ Associative Array

assocArray+=([key1]=value1)

Concatenation

Note

You may have noticed but Pushing is basically a concatenation of a 1-sized array for both types

๐Ÿ“ Array

array+=(elemN, elemM, elemO)

๐Ÿ—‚๏ธ Associative Array

assocArray+=([key1]=value1 [key2]=value2 [key3]=value3)

Targeted

๐Ÿ“ Array

array[0]=newElem1

Tip

You may set values for arbitrary indexes like just for array[13] & array[12] if you please

๐Ÿ—‚๏ธ Associative Array

assocArray[keyX]=valueX

Reading

Values

Individually

๐Ÿ“ Array

echo ${array[0]}

๐Ÿ—‚๏ธ Associative Array

echo ${assocArray[keyX]}

Altogether

Clean Mode

๐Ÿ“ Array

echo "${array[@]}"

๐Ÿ—‚๏ธ Associative Array

echo "${assocArray[@]}"
Gerbouli (๐Ÿคฎ) Mode

๐Ÿ“ Array

echo "${array[*]}"

๐Ÿ—‚๏ธ Associative Array

echo "${assocArray[*]}"

Indexes

echo "${!array[@]}"

๐Ÿ—‚๏ธ Associative Array

echo "${!assocArray[@]}"

Note

For either type of (Associative) Array the use of ${!array[@]} is equivalent to ${!array[*]} so have fun

Length

๐Ÿ“ Array || ๐Ÿ—‚๏ธ Associative Array

echo ${#struct[@]}

Warning

Don't mistake ${#struct[@]} with ${#struct[anIndex]} which would be the size of the value at anIndex in your struct

๐Ÿ›ฃ๏ธ RoadMap (no estimate)

  • Present this whole mess is a side by side array fashion
    • (which would be way nicer than currently considering how ironic this is that it is about arrays but is not presented in a very visually structured manner)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment