Shell bc calculator

来源:互联网 发布:知乐作品 编辑:程序博客网 时间:2024/05/18 03:17

Arithmetic expressions

Standard arithmetic operators (+ - * /) can be used to operate oninteger 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 analias, called for example, "MATH", that performs decimal arithmetic via thebc 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.

原创粉丝点击