Question

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`

Was it helpful?

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

OTHER TIPS

Try executing the script with

bash script.sh

or

ksh script.sh

I suspect your script is being executed by the default shell, which in HP-UX is (I believe) the POSIX shell, which does not support arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top