0

Dear I need something to help me in this. I'm trying to modify a global array through a function , using an auxiliary variable called "array". I would like to modify the global array "config " using a function that takes a string with the name of the variable " config".

I'm trying the following but I have not gotten results .

declare -A config

function testABC {
    array=${1}[@]
    array["key"]="value1"
    array["key2"]="value2"
}

testABC "config"
echo ${config["key"]}
echo ${config["key2"]}

#desired output:
#value1
#value2

My version of bash is 4.2.45

regards.

0

2 Answers 2

2

Use printf -v to set the value. This avoids an unsafe use of eval, as printf can only print text into a named variable, nothing more.

testABC () {
    printf -v "$1[key]" '%s' value1
    printf -v "$1[key2]" '%s' value2
}

Be sure to read http://mywiki.wooledge.org/BashFAQ/006 (from which this answer is taken) for a good understanding of the drawbacks of the various approaches. Shell languages simply aren't a good fit for this type of programming.

Sign up to request clarification or add additional context in comments.

Comments

1

You almost got it right, something like this should work:

function testABC {
  array="$1"
  # Don't proceed unless the argument is a valid identifier
  valid_id="^[[:alpha:]_][[:word:]]+$"
  [[ $array =~ $valid_id ]] || return

  eval "$array"["key"]="value1"
  eval "$array"["key2"]="value2"
}

We store the argument passed to the function in array variable. After that we construct line that assigns values to keys and use eval. eval replaces $array with "config" and executes the whole line, assigning the values properly.

1 Comment

Don't use eval without knowing that $1 is just the name of an array. You're allowing testABC to execute arbitrary code passed as an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.