1 #!/usr/bin/env bash
2
3 ### implicit for loop
4 # This is like "for i in $@".
5 func() {
6 for i; do
7 echo $i
8 done
9 }
10 func 1 2 3
11 # stdout-json: "1\n2\n3\n"
12
13 ### empty for loop (has "in")
14 set -- 1 2 3
15 for i in ; do
16 echo $i
17 done
18 # stdout-json: ""
19
20 ### for loop with invalid identifier
21 # should be compile time error, but runtime error is OK too
22 for - in a b c; do
23 echo hi
24 done
25 # stdout-json: ""
26 # status: 2
27 # OK bash/mksh status: 1
28
29 ### Tilde expansion within for loop
30 HOME=/home/bob
31 for name in ~/src ~/git; do
32 echo $name
33 done
34 # stdout-json: "/home/bob/src\n/home/bob/git\n"
35
36 ### Brace Expansion within Array
37 for i in -{a,b} {c,d}-; do
38 echo $i
39 done
40 # stdout-json: "-a\n-b\nc-\nd-\n"
41 # N-I dash stdout-json: "-{a,b}\n{c,d}-\n"
42
43 ### using loop var outside loop
44 func() {
45 for i in a b c; do
46 echo $i
47 done
48 echo $i
49 }
50 func
51 # status: 0
52 # stdout-json: "a\nb\nc\nc\n"
53
54 ### continue
55 for i in a b c; do
56 echo $i
57 if test $i = b; then
58 continue
59 fi
60 echo $i
61 done
62 # status: 0
63 # stdout-json: "a\na\nb\nc\nc\n"
64
65 ### break
66 for i in a b c; do
67 echo $i
68 if test $i = b; then
69 break
70 fi
71 done
72 # status: 0
73 # stdout-json: "a\nb\n"
74
75 ### continue at top level is error
76 # NOTE: bash and mksh both print warnings, but don't exit with an error.
77 continue
78 echo bad
79 # N-I bash/dash/mksh status: 0
80 # N-I bash/dash/mksh stdout: bad
81 # stdout-json: ""
82 # status: 1
83
84 ### break at top level is error
85 break
86 echo bad
87 # N-I bash/dash/mksh status: 0
88 # N-I bash/dash/mksh stdout: bad
89 # stdout-json: ""
90 # status: 1
91
92 ### while in while condition
93 # This is a consequence of the grammar
94 while while true; do echo cond; break; done
95 do
96 echo body
97 break
98 done
99 # stdout-json: "cond\nbody\n"
100
101 ### while in pipe
102 i=0
103 find tests/ | while read $path; do
104 i=$((i+1))
105 #echo $i
106 done
107 # This Because while loop was in a subshell
108 echo $i
109 # stdout: 0
110
111 ### while in pipe with subshell
112 i=0
113 find . -maxdepth 1 -name INSTALL.txt -o -name LICENSE.txt | ( while read path; do
114 i=$((i+1))
115 #echo $i
116 done
117 echo $i )
118 # stdout: 2
119
120 ### until loop
121 # This is just the opposite of while? while ! cond?
122 until false; do
123 echo hi
124 break
125 done
126 # stdout: hi