Bash: call array item by string

Viewed 36

How can I access array elements by string?

What I want to achieve is the following: I have a number of json files in a directory. These should be read in one after the other. All key values ​​("id", "test") should be configured / replaced. The changes should be saved in the json files.

#a json file example: 
{
  "id": "<fill-id>",
  "test": "<fill-test>"
}

The first key "id" should call the function "create_id". The second key "test" should call the function "create_test".

#!/bin/sh

declare -a FUNCTION
FUNCTION["id"]="create_id"
FUNCTION["test"]="create_test"
FUNCTION["secret"]="FUNCTION.C"

# read key/value from json file 
for filename in *.json; do
  while read -r key value; do
    declare "$key=$value"
    echo name: $key value: $value
     ${FUNCTION[$key]} $filename $value
  done < <(jq -r 'to_entries[] | "\(.key) \(.value)"' $filename)
done
1 Answers

You'll need to use an associative array, declare -A FUNCTION

BUT associative arrays are not a sh feature: declare -A is syntax. Change your #! line.

You'll also need bash version 4.0 or greater: the default /bin/bash on MacOSX is too old.

You can also find associative arrays in ksh and zsh.

Related