Arrays in a POSIX Compatible Shell

According to this checklist on hyperpolyglot.org , the following syntax can be used to set the array.

i=(1 2 3) 

But I get a dash error message, which by default is used for /bin/sh on Ubuntu and should be POSIX compatible.

 # 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 checklist erroneous or erroneous?
If so, what would be the correct way to define an array or list and be POSIX compatible?

+5
source share
2 answers

Posix does not specify arrays, so if you are limited by the capabilities of the Posix shell, you cannot use arrays.

I am afraid your link is wrong. Unfortunately, not everything you find on the Internet is true.

+5
source

As rici says , dashes do not support array. However, there are workarounds if you want to write a loop.

There will be no arrays for the loop, but you can do the splitting using the while + read builtin loop. Since the built-in dash reader also does not support delimiters, you also have to get by.

Here's an example script:

 myArray="abcd" echo $myArray | tr ' ' '\n' | while read item; do # use '$item' echo $item done 

This will be equivalent to bash code:

 myArray=(abcd) for item in ${myArray[@]}; do echo $item done 

If you want to get the nth element (say 2nd for example purposes):

 myArray="abcd" echo $myArray | cut -d\ -f2 # change -f2 to -fn 
+3
source

Source: https://habr.com/ru/post/1242966/


All Articles