Using arrays in a shell script -


i trying initialise array in shell script below

declare -a testarr=( 'a' 'b' ) 

also below

testarr=( 'a' 'b' ) 

but in both cases, following error

shell1.sh: 1: shell1.sh: syntax error: "(" unexpected 

can please tell me reason above error?

since want use posix shell , posix shell not support arrays, can "emulate" array in way:

set -- 'a' 'b' 

then have "array" available in posix shell ("$@") contains ($1) , b ($2).

and can pass array function, such as:

test() {     echo "$2" }  set -- 'a' 'b c' test "$@" 

if need save array can use following function:

arrsave() {     local     i;         printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"     done     echo " " } 

and use in following way:

set -- 'a' 'b c'  # save array arr=$(arrsave "$@")  # restore array eval "set -- $arr" 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -