Search code examples
shellhp-ux

Arrays for ksh and bash


I am writing a script to work both in bash and ksh. I have the following code

if [ -e /bin/ksh ]; then
       set -A arrayexample a b c
else
       arrayexample=('a' 'b' 'c')
fi

I have the following error message when I run it in ksh:

Syntax error at line 4:(' is not expected`


Solution

  • As others have noted it's better to test if the current shell is ksh by testing an environment variable. The location of the executable is too subject to changes. Then, though your else clause may not need to execute on ksh, it does need to parse. PD KSH v5.2.14 complains "ksh: syntax error: `(' unexpected" when parsing your else clause, while MIRBSD KSH R43 can parse and execute that syntax without error.

    Here's a function that works in either version of ksh, and bash, using eval to evade the parse problem:

    # example invocation:
    # A B [C D ...]
    # sets B[0]=C, B[1]=D, ...
    A()if [ "$KSH_VERSION" ]
       then set -A $1 "${@:2}"
       else eval $1='("${@:2}")'
       fi