Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error assigning associative array key with embedded period

I have a simple shell script in which I am trying to assign a value to an associative array where the key value has one or more "." characters in its value.

#!/bin/bash

X="my.key"
Y="my.val"

ARRAY[$X]=$Y

When I run this I get the following error message. my.key: syntax error: invalid arithmetic operator (error token is ".key")

How do I force bash to not treat my key like a floating point value?

Thanks in advance!

like image 783
Roger Kohler Avatar asked May 01 '13 21:05

Roger Kohler


1 Answers

In bash 4.x, associative arrays are not on by default, for backwards compatibility with 3.x and older (basically, you can use bare strings in array indexing, and they'll automatically be treated as variable references). Associative arrays must be explicitly declared before use to override this:

declare -A arrayname

Also, it's considered bad style to name script-local variables in all caps. All caps usually indicates an environment variable.

like image 142
michaelb958--GoFundMonica Avatar answered Sep 23 '22 18:09

michaelb958--GoFundMonica