Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays in a POSIX compliant shell

Tags:

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?

like image 388
zoom Avatar asked Feb 13 '16 22:02

zoom


People also ask

Which shells are 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.

Are bash arrays POSIX?

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.

Are there arrays in shell?

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.

What are arrays in shell script?

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.


1 Answers

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.

like image 88
rici Avatar answered Sep 21 '22 17:09

rici