help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Why bash does not recoganize array type smartly?


From: Stephane Chazelas
Subject: Re: [Help-bash] Why bash does not recoganize array type smartly?
Date: Tue, 15 Mar 2016 20:54:31 +0000
User-agent: Mutt/1.5.21 (2010-09-15)

2016-03-15 10:49:07 +0000, Dan Douglas:
> On Thu, Mar 10, 2016 at 4:16 AM, Peng Yu <address@hidden> wrote:
> > Is there any rationale why bash is defined in this way. Wouldn't it
> > better to allow users define associative array just by using something
> > like `x=([a]=1 [b]=2)` without having to declare it?
> 
> That's how it works in ksh93, but that's the only exception. In ksh93
> an initializer list that specifies indicies for sub-assignments is
> implicitly an associative array of strings until given another type. A
> compound assignment that's just a space-separated list of words is
> implicitly an arithmetic indexed array of strings.
>
> Everywhere else, it's always an indexed array unless you give it a type.

but in ksh93

a=()

declares a compound variable instead of an array unlike in all
other shells (bash, zsh, yash, rc, es)

a=(a=b b=c)

also declares a compound variable.

> bash/ksh93:
>     typeset -A arr=([foo]=bar) # Awesome
> bash/ksh93/zsh:
>     typeset -A arr; arr[foo]=bar arr[bar]=baz # Nasty but compatible
> 
> mksh has the problems of zsh in reverse -- it requires the assignment
> and the typeset to be separate commands (like zsh), and doesn't
> support associative arrays at all (unlike zsh), but at least it does
> support arr=([key]=value) syntax (also unlike zsh).
[...]

zsh's syntax to define an associative array as a whole is a lot
saner:

typeset -A a
a=(
  key1 value1
  key2 value2
)

That means, you can easily define associative arrays based on
the output of some command, or copy one array to another or
merge two arrays:

copy_of_a=("${(@kv)a}")

merge_of_a_and_b=("${(@kv)a}" "${(@kv)b}")

or

a+=("${(@kv)b}")

Note that since 5.1, zsh supports 

typeset -A a=(k1 v1 k2 v2)


-- 
Stephane




reply via email to

[Prev in Thread] Current Thread [Next in Thread]