Bash Arrays

Literal arrays

# literal array of four strings
arx=( a b c d )

# print the whole array, we can't just do $arx, because this is an Array!
echo ${arx[@]}

# Indexing an Array
echo ${arx[1]} # b

# get the length of the array
len=${#arx[@]}
# this also works, but will not quote internal array strings that might have the splitter
len2=${#arx[*]}

# last index of the array
last_element=$(( len - 1 ))

# Grab the last element of the array
echo ${arx[$(( len - 1 ))]} # echo d
# or
echo ${arx[(( len - 1 ))]} # omit the internal $
# or
echo ${arx[$(( ${#arx[@]} - 1 ))]}

# or even
echo ${arx[(( {#arx[@]} - 1 ))]}

dynamically created Arrays

IFS=":"; path_tokens=( $PATH ); unset IFS

# or

path_tokens=( $(echo $PATH | tr ":" " ") )

echo "PATH has ${#path_tokens[@]} tokens"

echo "$PATH"

len=${#path_tokens[@]}
echo "last path is ${path_tokens[(( len - 1 ))]}"

# or

echo "last path is ${path_tokens[(( $len - 1 ))]}"

# or

echo "last path is ${path_tokens[(( ${#path_tokens[@]} - 1 ))]}"

Slicing Arrays

https://stackoverflow.com/a/1336245/11003729

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")     # :1:2 takes a slice of length 2, starting at index 1.
C=("${A[@]:1}")       # slice to the end of the array
echo "${B[@]}"        # bar a  b c
echo "${B[1]}"        # a  b c
echo "${C[@]}"        # bar a  b c 42
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necessary

associative arrays

declare -A fruits

fruits["a"]="apples"
fruits["b"]="berries"
fruits["c"]="cherries"

echo "${fruits['a']}" # apples

# count of mappings
echo "${#fruits[@]}" # 3

# expands the values
echo "${fruits[@]}" # apples berries cherries

# expand the keys
echo "${!fruits[@]}"