Shell bc calculator

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值