OILS / spec / array-literal.test.sh View on Github | oils.pub

126 lines, 71 significant
1## compare_shells: bash
2
3#### [k1]=v1 (BashArray)
4# Note: This and next tests have originally been in "spec/assign.test.sh" and
5# compared the behavior of OSH's BashAssoc and Bash's indexed array. After
6# supporting "arr=([index]=value)" for indexed arrays, the test was adjusted
7# and copied here. See also the corresponding tests in "spec/assign.test.sh"
8a=([k1]=v1 [k2]=v2)
9echo ${a["k1"]}
10echo ${a["k2"]}
11## STDOUT:
12v2
13v2
14## END
15
16#### [k1]=v1 (BashAssoc)
17declare -A a
18a=([k1]=v1 [k2]=v2)
19echo ${a["k1"]}
20echo ${a["k2"]}
21## STDOUT:
22v1
23v2
24## END
25
26#### [k1]=v1 looking like brace expansions (BashArray)
27declare -A a
28a=([k2]=-{a,b}-)
29echo ${a["k2"]}
30## STDOUT:
31-{a,b}-
32## END
33
34#### [k1]=v1 looking like brace expansions (BashAssoc)
35a=([k2]=-{a,b}-)
36echo ${a["k2"]}
37## STDOUT:
38-{a,b}-
39## END
40## BUG bash STDOUT:
41[k2]=-a-
42## END
43
44#### BashArray cannot be changed to BashAssoc and vice versa
45declare -a a=(1 2 3 4)
46eval 'declare -A a=([a]=x [b]=y [c]=z)'
47echo status=$?
48argv.py "${a[@]}"
49
50declare -A A=([a]=x [b]=y [c]=z)
51eval 'declare -a A=(1 2 3 4)'
52echo status=$?
53argv.py $(printf '%s\n' "${A[@]}" | sort)
54## STDOUT:
55status=1
56['1', '2', '3', '4']
57status=1
58['x', 'y', 'z']
59## END
60
61#### s+=() with strict_array
62case $SH in bash) ;; *) shopt --set strict_array;; esac
63
64s1=hello
65s2=world
66
67# Overwriting Str with a new BashArray is allowed
68eval 's1=(1 2 3 4)'
69echo status=$?
70declare -p s1
71# Promoting Str to a BashArray is disallowed
72eval 's2+=(1 2 3 4)'
73echo status=$?
74declare -p s2
75## STDOUT:
76status=0
77declare -a s1=(1 2 3 4)
78status=1
79declare -- s2=world
80## END
81## N-I bash STDOUT:
82status=0
83declare -a s1=([0]="1" [1]="2" [2]="3" [3]="4")
84status=0
85declare -a s2=([0]="world" [1]="1" [2]="2" [3]="3" [4]="4")
86## END
87
88#### declare -A s+=() with strict_array
89case $SH in bash) ;; *) shopt --set strict_array;; esac
90
91s1=hello
92s2=world
93
94# Overwriting Str with a new BashAssoc is allowed
95eval 'declare -A s1=([a]=x [b]=y)'
96echo status=$?
97declare -p s1
98# Promoting Str to a BashAssoc is disallowed
99eval 'declare -A s2+=([a]=x [b]=y)'
100echo status=$?
101declare -p s2
102## STDOUT:
103status=0
104declare -A s1=(['a']=x ['b']=y)
105status=1
106declare -- s2=world
107## END
108## N-I bash STDOUT:
109status=0
110declare -A s1=([b]="y" [a]="x" )
111status=0
112declare -A s2=([0]="world" [b]="y" [a]="x" )
113## END
114
115#### assoc=(key value ...) is not allowed in the strict_array mode
116case $SH in bash) ;; *) shopt --set strict_array;; esac
117
118declare -A a=([a]=b)
119eval "a=(1 2 3 4)"
120declare -p a
121## STDOUT:
122declare -A a=()
123## END
124## N-I bash STDOUT:
125declare -A a=([3]="4" [1]="2" )
126## END