1 #!/usr/bin/env bash
2
3 #### (( )) result
4 (( 1 )) && echo True
5 (( 0 )) || echo False
6 ## stdout-json: "True\nFalse\n"
7
8 #### negative number is true
9 (( -1 )) && echo True
10 ## stdout: True
11
12 #### (( )) in if statement
13 if (( 3 > 2)); then
14 echo True
15 fi
16 ## stdout: True
17
18 #### (( ))
19 # What is the difference with this and let? One difference: spaces are allowed.
20 (( x = 1 ))
21 (( y = x + 2 ))
22 echo $x $y
23 ## stdout: 1 3
24
25 #### (( )) with arrays
26 a=(4 5 6)
27 (( sum = a[0] + a[1] + a[2] ))
28 echo $sum
29 ## stdout: 15
30 ## OK zsh stdout: 9
31
32 #### (( )) with error
33 (( a = 0 )) || echo false
34 (( b = 1 )) && echo true
35 (( c = -1 )) && echo true
36 echo $((a + b + c))
37 ## STDOUT:
38 false
39 true
40 true
41 0
42 ## END
43
44
45 #### bash and mksh: V in (( a[K] = V )) gets coerced to integer
46 K=key
47 V=value
48 typeset -a a
49 (( a[K] = V ))
50
51 # not there!
52 echo a[\"key\"]=${a[$K]}
53
54 echo keys = ${!a[@]}
55 echo values = ${a[@]}
56 ## STDOUT:
57 a["key"]=0
58 keys = 0
59 values = 0
60 ## END
61 ## N-I zsh status: 1
62 ## N-I zsh stdout-json: ""
63
64 #### bash: K in (( A[K] = V )) is a constant string
65 K=5
66 V=42
67 typeset -A A
68 (( A[K] = V ))
69
70 echo A["5"]=${A["5"]}
71 echo keys = ${!A[@]}
72 echo values = ${A[@]}
73 ## STDOUT:
74 A[5]=
75 keys = K
76 values = 42
77 ## END
78 ## N-I zsh status: 1
79 ## N-I zsh stdout-json: ""
80 ## N-I mksh status: 1
81 ## N-I mksh stdout-json: ""
82
83 #### BUG: (( V = A[K] )) doesn't retrieve the right value
84 typeset -A A
85 K=5
86 V=42
87 A["$K"]=$V
88 A["K"]=oops
89 A[K]=oops2
90
91 # We don't neither 42 nor "oops". Bad!
92 (( V = A[K] ))
93
94 echo V=$V
95 ## status: 1
96 ## stdout-json: ""
97 ## BUG bash/zsh status: 0
98 ## BUG bash/zsh STDOUT:
99 V=0
100 ## END
101
102 #### bash: V in (( A[K] = V )) gets coerced to integer
103 K=key
104 V=value
105 typeset -A A || exit 1
106 (( A[K] = V ))
107
108 # not there!
109 echo A[\"key\"]=${A[$K]}
110
111 echo keys = ${!A[@]}
112 echo values = ${A[@]}
113 ## STDOUT:
114 A["key"]=
115 keys = K
116 values = 0
117 ## END
118 ## N-I zsh stdout-json: ""
119 ## N-I zsh status: 1
120 ## N-I mksh stdout-json: ""
121 ## N-I mksh status: 1
122
123 #### literal strings not properly supported
124 declare -A A
125 A['x']=x
126 (( x = A['x'] ))
127 (( A['y'] = 'y' )) # y is a variable, gets coerced to 0
128 echo $x ${A['y']}
129 ## STDOUT:
130 0 0
131 ## END
132 ## N-I zsh/mksh STDOUT:
133 0
134 ## END