1 #!/usr/bin/env bash
2
3 # NOTE:
4 # -declare -A is required.
5 #
6 # Simply doing:
7 # a=([aa]=b [foo]=bar ['a+1']=c)
8 # gets utterly bizarre behavior.
9 #
10 # Associtative Arrays are COMPLETELY bash-specific. mksh doesn't even come
11 # close. So I will probably not implement them, or implement something
12 # slightly different, because the semantics are just wierd.
13
14 # http://www.gnu.org/software/bash/manual/html_node/Arrays.html
15 # TODO: Need a SETUP section.
16
17 ### TODO: SETUP should be share
18 declare -A a
19 a=([aa]=b [foo]=bar ['a+1']=c)
20
21 ### retrieve indices with !
22 declare -A a
23 a=([aa]=b [foo]=bar ['a+1']=c)
24 argv.py "${!a[@]}"
25 # Is this invalid on associative arrays? Makes no sense.
26 # stdout: ['aa', 'foo', 'a+1']
27
28 ### $a gives nothing
29 declare -A a
30 a=([aa]=b [foo]=bar ['a+1']=c)
31 echo "${a}"
32 # stdout-json: "\n"
33
34 ### length of dict does not work
35 declare -A a
36 a=([aa]=b [foo]=bar ['a+1']=c)
37 echo "${#a}"
38 # stdout: 0
39
40 ### index by number doesn't work
41 declare -A a
42 a=([aa]=b [foo]=bar ['a+1']=c)
43 echo 0 "${a[0]}" 1 "${a[1]}" 2 "${a[2]}"
44 # stdout-json: "0 1 2 \n"
45
46 ### index by key name
47 declare -A a
48 a=([aa]=b [foo]=bar ['a+1']=c)
49 echo "${a[aa]}" "${a[foo]}" "${a['a+1']}"
50 # WTF: Why do we get bar bar c?
51 # stdout-json: "b bar c\n"
52
53 ### index by quoted string
54 declare -A a
55 a=([aa]=b [foo]=bar ['a+1']=c)
56 echo "${a['a+1']}"
57 # stdout: c
58
59 ### index by unquoted string
60 declare -A a
61 a=([aa]=b [foo]=bar ['a+1']=c)
62 echo "${a[a+1]}"
63 # stdout: c
64
65 ### index by unquoted string as arithmetic
66 # For assoc arrays, unquoted string is just raw.
67 # For regular arrays, unquoted string is an arithmetic expression!
68 # How do I parse this?
69 declare -A assoc
70 assoc=([a+1]=c)
71 array=(5 6 7)
72 a=1
73 echo "${assoc[a]}"
74 echo "${assoc[a+1]}" # This works
75 echo "${array[a+1]}"
76 # stdout-json: "\nc\n7\n"
77
78 ### WTF index by key name
79 declare -A a
80 a=([xx]=bb [cc]=dd)
81 echo "${a[xx]}" "${a[cc]}"
82 # stdout-json: "bb dd\n"
83
84 ### Array stored in associative array gets converted to string
85 array=('1 2' 3)
86 declare -A d
87 d[a]="${array[@]}"
88 argv.py "${d[a]}"
89 # stdout: ['1 2 3']
90
91 ### Can't initialize assoc array with indexed array
92 declare -A A=(1 2 3)
93 # status: 1
94 # BUG bash status: 0
95
96 ### Initializing indexed array with with assoc array drops the constants
97 declare -a a=([xx]=1 [yy]=2 [zz]=3)
98 #declare -a a=(1 2 3)
99 echo "${a[@]}"
100 #echo "${!a[@]}"
101 # N-I mksh stdout-json: ""
102 # BUG bash stdout-json: "3\n"