Вопрос

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!

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top