3

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 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 ?

    2 Answers 2

    3
    eval "$ARRAY_NAME"'+=("$VARIABLE_VALUE")' 

    (would also work in zsh or ksh93).

    Your ksh88 one should be:

    eval 'set -A '"$ARRAY_NAME"' "${'"$ARRAY_NAME"'[@]}" "${VARIABLE_VALUE}"' 
      0

      I find that the following works in bash:

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

      The changes I made are (1) prepending eval and (2) escaping the parentheses that delimit the array we construct.

      However the same command run under ksh after replacing typeset -a with set -A fails. Would it be possible for you to either:

      • Get rid of typeset / set entirely (I think assigning an array to your variable implicitly sets its type), or

      • alter your code so that the two bits of shell-specific code are fully separated?

      In both cases, the snippet posted here seems fragile; it may be better to just use the appending operator +=, which seems to be available in both bash and ksh.

        You must log in to answer this question.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.