Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash interpreting associative array keys as octal numbers

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.

like image 954
Thomas Daniel Avatar asked Apr 06 '18 17:04

Thomas Daniel


People also ask

How to use associative array in Bash?

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?

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.

What are the basic array operations in Bash?

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.

What is an indexed array and associative array?

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.


1 Answers

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
like image 71
Charles Duffy Avatar answered Nov 15 '22 05:11

Charles Duffy