1 #!/usr/bin/env bash
2 #
3 # Constructs borrowed from ksh. Hm I didn't realize zsh also implements these!
4 # mksh implements most too.
5
6 #### C-style for loop
7 n=10
8 for ((a=1; a <= n ; a++)) # Double parentheses, and naked 'n'
9 do
10 if test $a = 3; then
11 continue
12 fi
13 if test $a = 6; then
14 break
15 fi
16 echo $a
17 done
18 ## status: 0
19 ## STDOUT:
20 1
21 2
22 4
23 5
24 ## END
25
26 #### For loop with and without semicolon
27 for ((a=1; a <= 3; a++)); do
28 echo $a
29 done
30 for ((a=1; a <= 3; a++)) do
31 echo $a
32 done
33 ## status: 0
34 ## STDOUT:
35 1
36 2
37 3
38 1
39 2
40 3
41 ## END
42
43 #### Accepts { } syntax too
44 for ((a=1; a <= 3; a++)) {
45 echo $a
46 }
47 ## STDOUT:
48 1
49 2
50 3
51 ## END
52
53 #### Empty init
54 i=1
55 for (( ;i < 4; i++ )); do
56 echo $i
57 done
58 ## status: 0
59 ## STDOUT:
60 1
61 2
62 3
63 ## END
64
65 #### Empty init and cond
66 i=1
67 for (( ; ; i++ )); do
68 if test $i = 4; then
69 break
70 fi
71 echo $i
72 done
73 ## status: 0
74 ## STDOUT:
75 1
76 2
77 3
78 ## END
79
80 #### Infinite loop with ((;;))
81 a=1
82 for (( ; ; )); do
83 if test $a = 4; then
84 break
85 fi
86 echo $((a++))
87 done
88 ## status: 0
89 ## STDOUT:
90 1
91 2
92 3
93 ## END