2

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?

3
  • 1
    Very likely your shebang is #!/bin/sh and not #!/bin/bash. Arrays are not supported in POSIX shells, but they are in Bash. Commented Dec 16, 2014 at 10:39
  • @gniourf_gniourf Ya sorry it is not bash. How can i use arrays in POSIX shells? Commented Dec 16, 2014 at 10:41
  • 3
    you can't. sh doesn't support arrays. If you need arrays, switch to Bash. Commented Dec 16, 2014 at 10:42

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.