shell perform mathematical operations

Integer:

  • expr
  • let
  • $(())
  • $[]

Float:

  • bc

1, expr

♦ There must be a space between the members involved in operations and operators:

 

 ♦ For those easily shell the wrong solution, before they passed expr command, you need to use the shell escape character (backslash '\') to escape. 

 ♦ To type a mathematical calculation result to a variable, use the command substitution to get the output expr command

We write a simple shell script as follows:

 Take a look at the operation result: no proper operation result is output

 We modify the script as follows:

  Let's look at the operation result: output 10

 2, the use of $ []

♦ In the bash shell, when a mathematical operation result is assigned to a variable, and can use the brackets dollar sign ($ [Operation]) to enclose a mathematical expression, and no escape escape. This same applies to the shell script. And there may be no space before the operation members and operators (expr requires spaces).

 3, using $ (())

 4, let

 bash shell supports only integer math operations. To make any real mathematical calculations, this is a huge limitation.

 Where we took a look at how to solve this problem.

There are several solutions to customer integer limit bash in mathematics shipped. The most common way is to use the built-in bash Keiki, called BC .

The basic usage 1. bc

bash calculator is actually a programming language that input floating-point expressions at the command line, and then interpret and evaluate expressions, and returns the result. bash meter is able to recognize:

?? numbers (integers and points)

?? variables (simple variables and arrays)

?? comments (/ * * / start line #, or C)

Expressions ??

?? programming (e.g., if-then)

Function ??

Bash counter can be accessed by bc command at a shell prompt:

 

 Floating-point operations are controlled by the built-in variable scale. This value must be set to the number of decimal places you want to keep count of fruit, or can not get the desired results.

 

 Default value of 0 is identified scale variable. Before the scale is set, the calculator is not calculated if the bash package also includes decimals. After it is set to 4, the results show bash Keiki comprises four decimal places. -q command line can not display a welcome message bash Timer. 

除了普通数字,bash计器还能支持变量。 

 bc 在shell脚本中的使用:用$()或者``替换命令赋值给变量,其中options部分一般设置精度scale,和变量赋值,expression部分是计算表达式

var=$(echo "option1,option2;...; expression" | bc) 

 或者var=`echo "option1;option2;...;expression"|bc`

 

除此之外还有一种写法:利用内联输入重定向(<<)

 

 

 

Guess you like

Origin www.cnblogs.com/qixifly/p/12030924.html