| 1 | #!/bin/bash |
| 2 | # max.sh: Maximum of two integers. |
| 3 | |
| 4 | E_PARAM_ERR=250 # If less than 2 params passed to function. |
| 5 | EQUAL=251 # Return value if both params equal. |
| 6 | # Error values out of range of any |
| 7 | #+ params that might be fed to the function. |
| 8 | |
| 9 | max2 () # Returns larger of two numbers. |
| 10 | { # Note: numbers compared must be less than 250. |
| 11 | if [ -z "$2" ] |
| 12 | then |
| 13 | return $E_PARAM_ERR |
| 14 | fi |
| 15 | |
| 16 | if [ "$1" -eq "$2" ] |
| 17 | then |
| 18 | return $EQUAL |
| 19 | else |
| 20 | if [ "$1" -gt "$2" ] |
| 21 | then |
| 22 | return $1 |
| 23 | else |
| 24 | return $2 |
| 25 | fi |
| 26 | fi |
| 27 | } |
| 28 | |
| 29 | max2 33 34 |
| 30 | return_val=$? |
| 31 | |
| 32 | if [ "$return_val" -eq $E_PARAM_ERR ] |
| 33 | then |
| 34 | echo "Need to pass two parameters to the function." |
| 35 | elif [ "$return_val" -eq $EQUAL ] |
| 36 | then |
| 37 | echo "The two numbers are equal." |
| 38 | else |
| 39 | echo "The larger of the two numbers is $return_val." |
| 40 | fi |
| 41 | |
| 42 | |
| 43 | exit 0 |
| 44 | |
| 45 | # Exercise (easy): |
| 46 | # --------------- |
| 47 | # Convert this to an interactive script, |
| 48 | #+ that is, have the script ask for input (two numbers). |