1

I'm not sure if this has been answered, I've looked and haven't found anything that looks like what I'm trying to do. I also posted this to stackexchange (https://unix.stackexchange.com/questions/189293/create-array-in-bash-with-variables-as-array-name)

I have a number of shell scripts that are capable of running against a ksh or bash shell, and they make use of arrays. I created a function named "setArray" that interrogates the running shell and determines what builtin to use to create the array - for ksh, set -A, for bash, typeset -a. However, I'm having some issues with the bash portion.

The function takes two arguments, the name of the array and the value to add. This then becomes ${ARRAY_NAME} and ${VARIABLE_VALUE}. Doing the following:

set -A $(eval echo \${ARRAY_NAME}) $(eval echo \${${ARRAY_NAME}[*]}) "${VARIABLE_VALUE}"

works perfectly in ksh. However,

typeset -a $(eval echo \${ARRAY_NAME})=( $(eval echo \${${ARRAY_NAME}[*]}) "${VARIABLE_VALUE}" )

does not. This provides

bash: syntax error near unexpected token '('

I know I can just make it a list of strings (e.g. MYARRAY="one two three") and just loop through it using the IFS, but I don't want to lose the ability to use an array either.

Any thoughts ?

10
  • 1
    typeset makes a variable local to the scope when you use it. That variable will not exist outside that function. Also why eval? And using [*] instead of quoted [@] means your array values can't include spaces (and that shell glob characters will get expanded). Commented Mar 10, 2015 at 15:53
  • Looking at linux.die.net/man/1/bash to find the syntax of the typeset -a I'm not seeing the parens. On the other hand, looking in the Arrays section of that same page it appears that simply var=(val1 val2 val3) does work. Haven't used arrays recently in bash so I'm just quoting the manual, but that would be where i would start. Commented Mar 10, 2015 at 15:59
  • I've tried it without the eval as well and it doesn't work - for example: typeset -a ${ARRAY_NAME} Commented Mar 10, 2015 at 15:59
  • Do you need this function at all? Does ksh not support array+=("newvalue")? Commented Mar 10, 2015 at 15:59
  • newer versions of ksh might but I'm hindered by ksh88 on old AIX boxes Commented Mar 10, 2015 at 16:01

1 Answer 1

1

Given the assertion that the ksh portion of this function is working only the bash portion needs to be created. For which the following should work and, I believe, be safe and robust (though evidence to the contrary is welcome).

eval $ARRAY_NAME+=\(\"\$VARIABLE_VALUE\"\)

First expansion only expands $ARRAY_NAME to get

eval array+=("$VARIABLE_VALUE")

which eval then causes to be evaluated again normally.

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

Comments

Your Answer

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