Arithmetic expressions
Standard arithmetic operators (+ - * /) can be used to operate on integer variable values. To save the results in another variable, however, you should use the @ command rather than the set command for the new variable. For example, you can increment a sum with the value of an argument like this:
- @ sum = 0 # initialize
@ sum = ( $sum + $1 )
Note that there must be a space between the @ command and the name of the variable that it is setting.
The C-shell cannot do floating point (decimal) arithmetic, for example, 1.1 * 2.3. However, you can invoke the bc calculator program from within a shell script to perform decimal arithmetic. Probably the simplest way to do that is to define an alias, called for example, "MATH", that performs decimal arithmetic via the bc program on the variables or constants passed to the alias. For example, you can define this alias in your script
- # Set MATH alias - takes an arithmetic assignment statement
# as argument, e.g., newvar = var1 + var2
# Separate all items and operators in the expression with blanks
alias MATH 'set \!:1 = `echo "\!:3-$" | bc -l`'
This says that the word "MATH" will be replaced by a set command which will set the variable given as the first word following the alias equal to the result of a math calculation specified by the remainder of the words following the alias, starting with the third word (skips the = sign), which is piped to the bc program to perform.
For example, you can use this MATH alias in a shell script to multiply two floating point values like this:
- set width = 20.8
set height = 5.4
MATH area = $width * $height
echo $area
Note to experts: normally, you would quote the asterisk character in a command line like the one shown above, so the shell does not try to interpret it as the filename wildcard matching character. But the alias expansion is done first, before filename matching, and as a result, the asterisk becomes protected by the quotes in the alias.