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 ### while in while condition
76 # This is a consequence of the grammar
77 while while true; do echo cond; break; done
78 do
79 echo body
80 break
81 done
82 # stdout-json: "cond\nbody\n"
83
84 ### while in pipe
85 i=0
86 find tests/ | while read $path; do
87 i=$((i+1))
88 #echo $i
89 done
90 # This Because while loop was in a subshell
91 echo $i
92 # stdout: 0
93
94 ### while in pipe with subshell
95 i=0
96 find . -maxdepth 1 -name INSTALL.txt -o -name LICENSE.txt | ( while read path; do
97 i=$((i+1))
98 #echo $i
99 done
100 echo $i )
101 # stdout: 2
102
103 ### until loop
104 # This is just the opposite of while? while ! cond?
105 until false; do
106 echo hi
107 break
108 done
109 # stdout: hi