| 1 | #!/bin/bash |
| 2 | # max2.sh: Maximum of two LARGE integers. |
| 3 | |
| 4 | # This is the previous "max.sh" example, |
| 5 | #+ modified to permit comparing large integers. |
| 6 | |
| 7 | EQUAL=0 # Return value if both params equal. |
| 8 | E_PARAM_ERR=-99999 # Not enough params passed to function. |
| 9 | # ^^^^^^ Out of range of any params that might be passed. |
| 10 | |
| 11 | max2 () # "Returns" larger of two numbers. |
| 12 | { |
| 13 | if [ -z "$2" ] |
| 14 | then |
| 15 | echo $E_PARAM_ERR |
| 16 | return |
| 17 | fi |
| 18 | |
| 19 | if [ "$1" -eq "$2" ] |
| 20 | then |
| 21 | echo $EQUAL |
| 22 | return |
| 23 | else |
| 24 | if [ "$1" -gt "$2" ] |
| 25 | then |
| 26 | retval=$1 |
| 27 | else |
| 28 | retval=$2 |
| 29 | fi |
| 30 | fi |
| 31 | |
| 32 | echo $retval # Echoes (to stdout), rather than returning value. |
| 33 | # Why? |
| 34 | } |
| 35 | |
| 36 | |
| 37 | return_val=$(max2 33001 33997) |
| 38 | # ^^^^ Function name |
| 39 | # ^^^^^ ^^^^^ Params passed |
| 40 | # This is actually a form of command substitution: |
| 41 | #+ treating a function as if it were a command, |
| 42 | #+ and assigning the stdout of the function to the variable "return_val." |
| 43 | |
| 44 | |
| 45 | # ========================= OUTPUT ======================== |
| 46 | if [ "$return_val" -eq "$E_PARAM_ERR" ] |
| 47 | then |
| 48 | echo "Error in parameters passed to comparison function!" |
| 49 | elif [ "$return_val" -eq "$EQUAL" ] |
| 50 | then |
| 51 | echo "The two numbers are equal." |
| 52 | else |
| 53 | echo "The larger of the two numbers is $return_val." |
| 54 | fi |
| 55 | # ========================================================= |
| 56 | |
| 57 | exit 0 |
| 58 | |
| 59 | # Exercises: |
| 60 | # --------- |
| 61 | # 1) Find a more elegant way of testing |
| 62 | #+ the parameters passed to the function. |
| 63 | # 2) Simplify the if/then structure at "OUTPUT." |
| 64 | # 3) Rewrite the script to take input from command-line parameters. |