| 1 | #!/bin/bash |
| 2 | # arith-tests.sh |
| 3 | # Arithmetic tests. |
| 4 | |
| 5 | # The (( ... )) construct evaluates and tests numerical expressions. |
| 6 | # Exit status opposite from [ ... ] construct! |
| 7 | |
| 8 | (( 0 )) |
| 9 | echo "Exit status of \"(( 0 ))\" is $?." # 1 |
| 10 | |
| 11 | (( 1 )) |
| 12 | echo "Exit status of \"(( 1 ))\" is $?." # 0 |
| 13 | |
| 14 | (( 5 > 4 )) # true |
| 15 | echo "Exit status of \"(( 5 > 4 ))\" is $?." # 0 |
| 16 | |
| 17 | (( 5 > 9 )) # false |
| 18 | echo "Exit status of \"(( 5 > 9 ))\" is $?." # 1 |
| 19 | |
| 20 | (( 5 == 5 )) # true |
| 21 | echo "Exit status of \"(( 5 == 5 ))\" is $?." # 0 |
| 22 | # (( 5 = 5 )) gives an error message. |
| 23 | |
| 24 | (( 5 - 5 )) # 0 |
| 25 | echo "Exit status of \"(( 5 - 5 ))\" is $?." # 1 |
| 26 | |
| 27 | (( 5 / 4 )) # Division o.k. |
| 28 | echo "Exit status of \"(( 5 / 4 ))\" is $?." # 0 |
| 29 | |
| 30 | (( 1 / 2 )) # Division result < 1. |
| 31 | echo "Exit status of \"(( 1 / 2 ))\" is $?." # Rounded off to 0. |
| 32 | # 1 |
| 33 | |
| 34 | (( 1 / 0 )) 2>/dev/null # Illegal division by 0. |
| 35 | # ^^^^^^^^^^^ |
| 36 | echo "Exit status of \"(( 1 / 0 ))\" is $?." # 1 |
| 37 | |
| 38 | # What effect does the "2>/dev/null" have? |
| 39 | # What would happen if it were removed? |
| 40 | # Try removing it, then rerunning the script. |
| 41 | |
| 42 | # ======================================= # |
| 43 | |
| 44 | # (( ... )) also useful in an if-then test. |
| 45 | |
| 46 | var1=5 |
| 47 | var2=4 |
| 48 | |
| 49 | if (( var1 > var2 )) |
| 50 | then #^ ^ Note: Not $var1, $var2. Why? |
| 51 | echo "$var1 is greater than $var2" |
| 52 | fi # 5 is greater than 4 |
| 53 | |
| 54 | exit 0 |