According to this reference sheet on hyperpolyglot.org, the following syntax can be used to set an array.
i=(1 2 3)
But I get an error with dash which is the default for /bin/sh
on Ubuntu and should be POSIX compliant.
# Trying the syntax with dash in my terminal
> dash -i
$ i=(1 2 3)
dash: 1: Syntax error: "(" unexpected
$ exit
# Working fine with bash
> bash -i
$ i=(1 2 3)
$ echo ${i[@]}
1 2 3
$ exit
Is the reference sheet misleading or erroneous?
If yes, what would be the correct way to define an array or a list and be POSIX compliant?
Since POSIX is a specification, there is no shell called POSIX shell. You can use POSIX standard in many shells such as, dash , bash , ksh , mksh , yash , zsh , etc. You need to be aware that each shell has its own commands and options or different options top of the POSIX specification.
POSIX Shell Arrays. Compared to a basic POSIX-compliant shell, bash arrays are much more powerful and convenient to use. Let's illustrate this by trying to create an indexed array and access its 3rd member. We can see that bash has a much cleaner syntax for arrays, making it easier to use for more complex operations.
The shell supports one-dimensional arrays. The maximum number of array elements is 1,024. When an array is defined, it is automatically dimensioned to 1,024 elements.
An array is a systematic arrangement of the same type of data. But in Shell script Array is a variable which contains multiple values may be of same type or different type since by default in shell script everything is treated as a string. An array is zero-based ie indexing start with 0.
Posix does not specify arrays, so if you are restricted to Posix shell features, you cannot use arrays.
I'm afraid your reference is mistaken. Sadly, not everything you find on the internet is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With