| 1 | #!/bin/bash |
| 2 | # hypotenuse.sh: Returns the "hypotenuse" of a right triangle. |
| 3 | # (square root of sum of squares of the "legs") |
| 4 | |
| 5 | ARGS=2 # Script needs sides of triangle passed. |
| 6 | E_BADARGS=85 # Wrong number of arguments. |
| 7 | |
| 8 | if [ $# -ne "$ARGS" ] # Test number of arguments to script. |
| 9 | then |
| 10 | echo "Usage: `basename $0` side_1 side_2" |
| 11 | exit $E_BADARGS |
| 12 | fi |
| 13 | |
| 14 | |
| 15 | AWKSCRIPT=' { printf( "%3.7f\n", sqrt($1*$1 + $2*$2) ) } ' |
| 16 | # command(s) / parameters passed to awk |
| 17 | |
| 18 | |
| 19 | # Now, pipe the parameters to awk. |
| 20 | echo -n "Hypotenuse of $1 and $2 = " |
| 21 | echo $1 $2 | awk "$AWKSCRIPT" |
| 22 | # ^^^^^^^^^^^^ |
| 23 | # An echo-and-pipe is an easy way of passing shell parameters to awk. |
| 24 | |
| 25 | exit |
| 26 | |
| 27 | # Exercise: Rewrite this script using 'bc' rather than awk. |
| 28 | # Which method is more intuitive? |