Reputation: 135
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
Reputation: 15996
If I understand your question, I think you need associative arrays in bash. 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 bash version 4.0 or greater.
Upvotes: 2