Reputation: 7023
I am trying to initialise an array in a shell script like below
declare -a testArr=( 'A' 'B' )
Also like below
testArr=( 'A' 'B' )
But in both the cases, I get the following error
shell1.sh: 1: shell1.sh: Syntax error: "(" unexpected
Can someone please tell me the reason for the above error?
Upvotes: 2
Views: 520
Reputation: 766
Since you want to use POSIX shell and POSIX shell does not support arrays, you can "emulate" array in this way:
set -- 'A' 'B'
Then you will have the only "array" available in POSIX shell ("$@") that contains A ($1) and B ($2).
And you can pass this array to another function, such as:
test() {
echo "$2"
}
set -- 'A' 'B C'
test "$@"
If you need to save the array you can use the following function:
arrsave() {
local i
for i; do
printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"
done
echo " "
}
And use it in the following way:
set -- 'A' 'B C'
# Save the array
arr=$(arrsave "$@")
# Restore the array
eval "set -- $arr"
Upvotes: 3