Introducing UNIX and Linux |
More on shellsOverview |
Arithmetic expansionThe utility
where expression is a valid arithmetic expression,
using only integers (no floating point arithmetic), and the
operators described below. On some On some non-POSIX systems, you
will need to use
As an example, the following script will read in a number, assumed to represent pounds weight, and write to the standard output a message translating that to stones and pounds (one stone = 14 pounds): echo Type in a whole number representing pounds weight: read POUNDS STONES=$(( $POUNDS / 14 )) SMALLPOUNDS=$(( $POUNDS % 14 )) echo $POUNDS pounds is $STONES and $SMALLPOUNDS pounds Worked exampleWrite a script
# Prompt the user and read in number of seconds echo Enter a number of seconds: read SECONDS if [ $SECONDS -lt 0 ] # Check it's positive then echo Number must be positive else MINUTES=$(( $SECONDS / 60 )) # Total minutes RSECONDS=$(( $SECONDS % 60 )) # Residual seconds HOURS=$(( $MINUTES / 60 )) # Total hours MINUTES=$(( $MINUTES % 60 )) # Residual minutes printf "%d seconds is %d:%02d:%02d\n" $SECONDS \ $HOURS $MINUTES $RSECONDS fi You may wish to compare arithmetic expansion with using
i=1 while [ $i -le 12 ] do result=$(( $i * 12 )) echo "$i x 12 = $result" i=$(( $i + 1 )) done Try out both - you will find that when you use arithmetic
expansion it is much faster. Where possible, you should use
arithmetic expansion in preference to |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck