Fun Bash Script: numerical calculation, bash script Numerical Calculation

Source: Internet
Author: User

Fun Bash Script: numerical calculation, bash script Numerical Calculation

6th articles

The mathematical operations in Bash are not as simple as other languages, because Bash treats all variables as strings, so a = 1 + 2, a is not equal to 3, but equal to string 1 + 2.

There are several solutions to solve this problem.



$ Is only the meaning of the variable value. Brackets and expressions can be considered as a variable. You can directly use the variable name by referencing the variable in brackets, or use $ to add the variable name. For example:

C = $ [$ a + $ B]

Of course, you can directly use the literal value:


Note that:

  • This operation only supports integers. If a or B is a decimal number, an error is returned. The operation results are decimal and will be automatically rounded up.
  • There can be spaces between the operator (+-*/) of this operation [] and the variable. Write c = $ [a + B]
Operator (())

The method is similar to [], and the precautions are similar.

Expr and Its Anti-reference common Computation

Expr is an external command (non-Bash command), so it is independent of Bash and can also be used in other shells.

a=2b=3expr $a + $bexpr $a - $bexpr $a \* $bexpr $a / $bexpr $a % $b
Note that:

  • Between operators and operandsBe sureSpace Interval
  • The operand (that is, the variable) must have a $ character before it.
  • Multiplication Number *, escape with backslash \
  • This command prints the calculation result to the standard output.
  • Only integer operations are supported.
  • You can also directly use the literal value of a number.

In addition to the preceding operations, expr also supports other operations. You can view them by using man expr.


So how to assign the calculation result of expr to a variable? The answer is: Anti-reference.

I introduced the concept of replacing initialization with commands in the variable and initialization section. Anti-reference is only a method of command replacement.

c=`expr $a + $b`
Basic Format for floating point calculation using bc

The various numerical calculation solutions we introduced above all have a problem, whether inside shell or outside, that is, they do not support decimal operations. This should be determined by the use environment of the shell itself. There may not be many cases of decimal operations in the script.

What if we want to perform a floating point number operation? The answer is to use an external tool (or command) bc. Bc is an interactive calculator. You can type bc in the shell to enter the command prompt of bc. However, bc also supports writing data to scripts for numerical calculation. This requires pipelines. The so-called pipelines are the standard output of the previous command, which is passed as the standard input to the subsequent commands. For more information about MPs queues, I/O operations will be mentioned later.

echo '45.36-22.33'|bc
Double quotation marks. The implementation process is to pass a mathematical expression to the bc calculator. Then bc prints the result to the standard output.

Set precision

A very important concept in floating-point operations is accuracy. The precision here in bc refers to the number of digits in decimal places. When using bc for Division operations, you will find that the default value is integer, that is, there is no fractional part.

For example, echo '200' | bc, which outputs 0. Because the default precision of bc is 0. The possible solution you may think of is echo '2. 0/3 '| bc. However, the output result is still 0.

Other operations, such as addition, subtraction, and multiplication. The maximum precision in the operand is the precision of the output result.

echo '2.0*3.00'|bcecho '2.25+4.5'|bcecho '5.66-7.888'|bc
Output result:

But Division does not work. You must set it manually.
 echo 'scale=3;2/3'|bc.666
. 666 is the output result. Because the precision is set to scale = 3. Leading 0 is ignored.

Bc is powerful, and you can even directly use bc for hexadecimal conversion.

Hexadecimal conversion

Obase is the output base and ibase is the input base.

Auto-increment and auto-Increment

In C, auto-increment and auto-increment operations are supported. That is, a ++, B --, c ++ = 2, d-= 3. The meaning is no longer described.

Note the following two points for auto-increment and auto-increment operations:

To implement this function in Bash, you need to use the commandLet(Internal commands ).

I used Ubuntu1204 in Linux for the first time and started Shell (Bash) programming. I found that Shell originally does not support numerical computation.

You need to make it clear that shell is not used for numerical calculation. Numeric operations can use the C language you are familiar. For simple numeric calculation, you can use awk or perl. In awk or perl, you can use operators and expressions that are familiar with Class c. Bash supports Simple integer operations. This function is provided by the let or () operator. I think that since you are interested in learning shell, you will read books about shell, which will certainly introduce these contents. You don't wish you good luck ~
Ps: some books about shell (these books will tell you where it is used by linux/shell)
Advanced bash scripting guide
Unix concepts and applications
Laruence linux Private food

Use bash scripts to describe how to execute remote commands in batches on a large number of remote servers

Publish the script to be run on the master, run the listener on each remote server, and poll the script published by the master segment, such

Ver =
While true; do
Nextver = ''
If ["$ ver "! = "$ Nextver"]; then>/tmp/script
Chmod + x/tmp/script
Ver = "$ nextver"
Sleep 60

Hope to help!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.