1 |
#!/bin/bash |
2 |
# |
3 |
# Differences from bash: |
4 |
# - literal syntax alternates key-value |
5 |
# - (@k) syntax for keys. Although this is sort of like my ${@array} syntax |
6 |
# for arrays. |
7 |
# - zsh allows $a[$k], not just ${a[$k]} |
8 |
|
9 |
|
10 |
### TODO: SETUP should be shared |
11 |
typeset -A a |
12 |
a=(aa b foo bar a+1 c) |
13 |
|
14 |
### retrieve key |
15 |
typeset -A a |
16 |
a=(aa b foo bar a+1 c) |
17 |
echo ${a[aa]} |
18 |
# stdout: b |
19 |
|
20 |
### set key |
21 |
typeset -A a |
22 |
a=(aa b foo bar a+1 c) |
23 |
a[X]=XX |
24 |
argv.py "${a[@]}" |
25 |
# What order is this? |
26 |
# stdout: ['bar', 'b', 'c', 'XX'] |
27 |
|
28 |
### iterate over keys |
29 |
typeset -A assoc |
30 |
assoc=(k1 v1 k2 v2 k3 v3) |
31 |
for k in "${(@k)assoc}"; do |
32 |
echo "$k: $assoc[$k]" |
33 |
done |
34 |
# stdout-json: "k1: v1\nk2: v2\nk3: v3\n" |
35 |
|
36 |
### iterate over both keys and values |
37 |
typeset -A assoc |
38 |
assoc=(k1 v1 k2 v2 k3 v3) |
39 |
for k v ("${(@kv)assoc}"); do |
40 |
echo "$k: $v" |
41 |
done |
42 |
# stdout-json: "k1: v1\nk2: v2\nk3: v3\n" |
43 |
|
44 |
### get length |
45 |
typeset -A assoc |
46 |
assoc=(k1 v1 k2 v2 k3 v3) |
47 |
echo ${#assoc} ${#assoc[k1]} |
48 |
# stdout: 3 2 |
49 |
|
50 |
### index by integer does not work |
51 |
typeset -A assoc |
52 |
assoc=(k1 v1 k2 v2 k3 v3) |
53 |
argv.py "${assoc[1]}" |
54 |
# stdout: [''] |