Mansuro Mansuro - 1 month ago 9x
Bash Question

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
arrayexample=('a' 'b' 'c')

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

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


As others have noted better to test if the current shell is ksh, not whether some file happens to exist. Then, though your else clause may not execute on ksh, ksh parses the entire compound statement before it executes the appropriate parts. 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 ksh&bash, using eval to evade parse problems:

# 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}")'