1 #!/usr/bin/env bash
2 #
3 # Test arithmetic expressions in all their different contexts.
4
5 # $(( 1 + 2 ))
6 # (( a=1+2 ))
7 # ${a[ 1 + 2 ]}
8 # ${a : 1+2 : 1+2}
9 # a[1 + 2]=foo
10
11 ### Multiple right brackets inside expression
12 a=(1 2 3)
13 echo ${a[a[0]]} ${a[a[a[0]]]}
14 # stdout: 2 3
15 # N-I zsh status: 0
16 # N-I zsh stdout-json: "\n"
17
18 ### Slicing of string with constants
19 s='abcd'
20 echo ${s:0} ${s:0:4} ${s:1:1}
21 # stdout: abcd abcd b
22
23 ### Slicing of string with variables
24 s='abcd'
25 zero=0
26 one=1
27 echo ${s:$zero} ${s:$zero:4} ${s:$one:$one}
28 # stdout: abcd abcd b
29
30 ### Array index on LHS of assignment
31 a=(1 2 3)
32 zero=0
33 a[zero+5-4]=X
34 echo ${a[@]}
35 # stdout: 1 X 3
36 # OK zsh stdout: X 2 3
37
38 ### Array index on LHS with spaces
39 # zsh fails to parse this because of the spaces.
40 a=(1 2 3)
41 zero=0
42 a[zero + 5 - 4]=X
43 echo ${a[@]}
44 # stdout: 1 X 3
45 # BUG zsh stdout-json: ""
46 # BUG zsh status: 1
47
48 ### Array index on LHS with indices
49 a=(1 2 3)
50 a[a[1]]=X
51 echo ${a[@]}
52 # stdout: 1 2 X
53 # OK zsh stdout: X 2 3
54
55 ### Slicing of string with expressions
56 # mksh accepts ${s:0} and ${s:$zero} but not ${s:zero}
57 # zsh says unrecognized modifier 'z'
58 s='abcd'
59 zero=0
60 echo ${s:zero} ${s:zero+0} ${s:zero+1:zero+1}
61 # stdout: abcd abcd b
62 # BUG mksh stdout-json: ""
63 # BUG mksh status: 1
64 # BUG zsh stdout-json: ""
65 # BUG zsh status: 1
66
67 ### Ambiguous colon in slice
68 s='abcd'
69 echo $(( 0 < 1 ? 2 : 0 )) # evalutes to 2
70 echo ${s: 0 < 1 ? 2 : 0 : 1} # 2:1 -- TRICKY THREE COLONS
71 # stdout-json: "2\nc\n"
72 # BUG mksh stdout-json: "2\n"
73 # BUG mksh status: 1
74 # BUG zsh stdout-json: "2\n"
75 # BUG zsh status: 1
76
77 ### Triple parens should be disambiguated
78 # The first paren is part of the math, parens 2 and 3 are a single token ending
79 # arith sub.
80 ((a=1 + (2*3)))
81 echo $a $((1 + (2*3)))
82 # stdout: 7 7
83
84 ### Quadruple parens should be disambiguated
85 ((a=1 + (2 * (3+4))))
86 echo $a $((1 + (2 * (3+4))))
87 # stdout: 15 15
88
89 ### Alternative $[] syntax
90 echo $[1 + 2] "$[3 * 4]"
91 # stdout: 3 12
92 # N-I mksh stdout: $[1 + 2] $[3 * 4]