Bash · 2522 bytes Raw Blame History
1 #!/bin/sh
2 TEST_PREFIX="[arithmetic]"
3 . "$(cd "$(dirname "$0")" && pwd)/test_harness.sh"
4
5 section "1. basic arithmetic"
6 compare_output "addition" 'echo $((3 + 4))'
7 compare_output "subtraction" 'echo $((10 - 3))'
8 compare_output "multiplication" 'echo $((6 * 7))'
9 compare_output "division" 'echo $((20 / 4))'
10 compare_output "modulo" 'echo $((17 % 5))'
11 compare_output "negative result" 'echo $((3 - 10))'
12 compare_output "zero division guard" 'echo $((0 / 1))'
13
14 section "2. operator precedence"
15 compare_output "multiply before add" 'echo $((2 + 3 * 4))'
16 compare_output "parentheses override" 'echo $(( (2 + 3) * 4 ))'
17 compare_output "nested parentheses" 'echo $(( (2 + 3) * (4 - 1) ))'
18 compare_output "complex expression" 'echo $(( 10 / 2 + 3 * 4 - 1 ))'
19
20 section "3. comparison and ternary"
21 compare_output "ternary true" 'echo $((5 > 3 ? 5 : 3))'
22 compare_output "ternary false" 'echo $((2 > 3 ? 2 : 3))'
23 compare_output "equality" 'echo $((5 == 5))'
24 compare_output "inequality" 'echo $((5 != 3))'
25 compare_output "less than" 'echo $((3 < 5))'
26 compare_output "greater than" 'echo $((5 > 3))'
27 compare_output "logical AND" 'echo $((1 && 1))'
28 compare_output "logical OR" 'echo $((0 || 1))'
29 compare_output "logical NOT" 'echo $((!0))'
30
31 section "4. increment and decrement"
32 compare_output "post-increment" 'x=5; echo $((x++)); echo $x'
33 compare_output "pre-increment" 'x=5; echo $((++x)); echo $x'
34 compare_output "post-decrement" 'x=5; echo $((x--)); echo $x'
35 compare_output "pre-decrement" 'x=5; echo $((--x)); echo $x'
36
37 section "5. bitwise operations"
38 compare_output "bitwise AND" 'echo $((12 & 10))'
39 compare_output "bitwise OR" 'echo $((12 | 10))'
40 compare_output "bitwise XOR" 'echo $((12 ^ 10))'
41 compare_output "bitwise NOT" 'echo $((~0))'
42 compare_output "left shift" 'echo $((1 << 4))'
43 compare_output "right shift" 'echo $((16 >> 2))'
44
45 section "6. compound assignment"
46 compare_output "+= assignment" 'x=10; echo $((x += 5))'
47 compare_output "-= assignment" 'x=10; echo $((x -= 3))'
48 compare_output "*= assignment" 'x=4; echo $((x *= 3))'
49 compare_output "/= assignment" 'x=20; echo $((x /= 4))'
50 compare_output "%= assignment" 'x=17; echo $((x %= 5))'
51
52 section "7. variables in arithmetic"
53 compare_output "variable reference" 'a=10; b=20; echo $((a + b))'
54 compare_output "unset var is zero" 'unset V; echo $((V + 5))'
55 compare_output "assignment in expression" 'echo $((x = 5 + 3)); echo $x'
56 compare_output "chained assignment" 'echo $((x = y = 5)); echo $x $y'
57 compare_output "comma operator" 'echo $((x=1, y=2, x+y))'
58
59 print_summary