1 # spec/oil-for
2
3 #### For loop over expression: list
4 var mylist = [1, 2, 3]
5 for item in (mylist) {
6 echo "item $item"
7 }
8
9 ## STDOUT:
10 item 1
11 item 2
12 item 3
13 ## END
14
15 #### For loop over expression: dict
16
17 var mydict = {name: 'bob', age: 40}
18 for key in (mydict) {
19 echo "key $key"
20 }
21
22
23 ## STDOUT:
24 key name
25 key age
26 ## END
27
28
29 #### For loop over expression: range (low priority)
30 var myrange = 0:3
31 for i in (myrange) {
32 echo "i $key"
33 }
34
35 ## STDOUT:
36 i 0
37 i 1
38 i 2
39 ## END
40
41 #### Shell for loop with index (equivalent of enumerate())
42 for i, item in a b c {
43 echo "$i $item"
44 }
45 ## STDOUT:
46 0 a
47 1 b
48 2 c
49 ## END
50
51 #### 3 indices with (mylist) is a runtime error
52 for i, item bad in (['foo', 'bar']) {
53 echo "$i $item $bad"
54 }
55 ## status: 2
56
57 #### Shell for loop can't have 3 indices
58 for i, bad, bad in a b c {
59 echo $i $item
60 }
61 ## status: 2
62
63 #### Any for loop can't have 4 indiecs
64 for a, b, c, d in (['foo']) {
65 echo $i $item
66 }
67 ## status: 2
68
69 #### Expression for loop with index: list
70 for i, item in (['spam', 'eggs']) {
71 echo "$i $item"
72 }
73 ## STDOUT:
74 0 spam
75 1 eggs
76 ## END
77
78 #### Expression for loop with index: dict (TODO: define dict iter order)
79 for key, value in ({name: 'bob', age: 40}) {
80 echo "pair $key $value"
81 }
82 ## STDOUT:
83 pair name bob
84 pair age 40
85 ## END
86
87 #### dict: index key value loop (TODO: define dict iter order)
88 for i, key, value in ({name: 'bob', age: 40}) {
89 echo "entry $i $key $value"
90 }
91 ## STDOUT:
92 entry 0 name bob
93 entry 1 age 40
94 ## END
95
96
97 #### Equivalent of zip()
98
99 var array = %(d e f)
100
101 for i, item in a b c {
102 echo "$i $item $[array[i]]"
103 }
104
105 ## STDOUT:
106 0 a d
107 1 b e
108 2 c f
109 ## END
110
111 #### Iterate over shell data structures
112
113 # TODO: use new style
114
115 declare array=(one two three)
116 for item in (array) {
117 echo $item
118 }
119
120 echo ---
121
122 declare -A A=([k]=v [k2]=v2) # iterate over keys
123 for key in (A) {
124 echo $key
125 }
126 ## STDOUT:
127 one
128 two
129 three
130 ---
131 k
132 k2
133 ## END
134
135
136
137 #### parse_bare_word eliminates confusion
138
139 shopt --unset parse_bare_word
140
141 for x in mylist { # THIS FAILS
142 echo "BAD $x"
143 }
144
145 ## status: 2
146 ## STDOUT:
147 ## END
148
149
150 #### Object that's not iterable
151
152 echo hi
153 for x in (42) {
154 echo $x
155 }
156
157 ## status: 3
158 ## STDOUT:
159 hi
160 ## END
161
162 #### Oil for with brace substitution and glob
163
164 touch {foo,bar}.py
165 for i, file in *.py {README,foo}.md {
166 echo "$i $file"
167 }
168 ## STDOUT:
169 0 bar.py
170 1 foo.py
171 2 README.md
172 3 foo.md
173 ## END