How do I prevent this from failing:
a[5c8]=1
-bash: 5c8: value too great for base (error token is "5c8")
It seems that bash interprets 5c8 as an octal number. Obviously, I could add a prefix to the key and remove that prefix later when using the array, but I was hoping for a more elegant solution.
Bash 4.3.48.
An associative array uses a "key" to map the value instead of index positions. Let’s dive in and see how to use associative array in bash. Unlike an Indexed array, you cannot initialize an associative array without using declare command. Use the declare command with -A flag. Now an empty array named "STAR_PLAYERS" is created.
how can we retrieve the keys and values of the associative array? In Bash, to get keys of an associative array via indirection, given the name of the array in variable dictvar one can leverage declare or local ( original source ): An alternative using eval is suggested in this answer.
This guide covers the standard bash array operations and how to declare ( set ), append, iterate over ( loop ), check ( test ), access ( get ), and delete ( unset) a value in an indexed bash array and an associative bash array. The detailed examples include how to sort and shuffle arrays.
An indexed array is an array in which the keys (indexes) are ordered integers. You can think about it as an ordered list of items. Then, an associative array, a.k.a hash table, is an array in which the keys are represented by arbitrary strings. How to declare a Bash Array? Arrays in Bash are one-dimensional array variables.
All array keys are interpreted as numbers (or names of variables to be evaluated to obtain a number) unless you declare the array as associative, as with declare -A
:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[1-3].*) echo "Bash 4.0+ required" >&2; exit 1;; esac
declare -A a
a[5c8]=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With