Your question is about "Unix shell scripts," but tagged as bash . These are two different answers.
The POSIX shell specification has nothing to do with arrays, as the original Bourne shell did not support them. Even today on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh does not support an array. Therefore, if you want your script to work in different Bourne-compatible shells, you should not use them. Alternatively, if you are proposing a specific shell, be sure to include its full name in the shebang line, for example #!/usr/bin/env bash .
If you are using bash or zsh or a modern version of ksh , you can create an array as follows:
myArray=(first "second element" 3rd)
and access such items
$ echo "${myArray[1]}" second element
You can get all the items through "${myArray[@]}" . You can use the slice notation $ {array [@]: start: length} to limit the part of the array referenced, for example, "${myArray[@]:1}" to skip the first element.
The length of the array is ${#myArray[@]} . You can get a new array containing all indexes from an existing array using "${!myArray[@]}" .
Older versions of ksh prior to ksh93 also had arrays, but not parenthesized notations, nor did they support slicing. You can create an array as follows:
set -A myArray -- first "second element" 3rd
Mark Reed Dec 09 '15 at 16:24 2015-12-09 16:24
source share