outrunthewolf
outrunthewolf

Reputation: 135

String to become a Variable in bash

I've written this language free as i'm not 100% sure how to do it in bash.

I'd like to take an array like the following:

array=('address'=> '127.0.0.1', 'port' => '22')

And then access the array key as a variable in bash like so:

$address=127.0.01
echo $address

127.0.0.1

Thanks.

Upvotes: 0

Views: 72

Answers (1)

Digital Trauma
Digital Trauma

Reputation: 15996

If I understand your question, I think you need associative arrays in . These need to be explicitly declared with declare -A:

$ declare -A array
$ array[address]=127.0.0.1
$ array[port]=22
$ key=address
$ echo ${array[$key]}
127.0.0.1
$ key=port
$ echo ${array[$key]}
22
$ echo ${!array[@]}
address port
$ echo ${array[@]}
127.0.0.1 22
$ 

You can also assign multiple elements at once:

$ array=([address]=127.0.0.1 [port]=22)
$

You can iterate over the associative array:

$ for key in ${!array[@]}; do
>     echo "key=\"$key\", array[$key]=\"${array[$key]}\""
> done
key="address", array[address]="127.0.0.1"
key="port", array[port]="22"
$ 

Note associative arrays are only available in version 4.0 or greater.

Upvotes: 2

Related Questions