Mathematical calculation of variables in Linux shell scripts

Source: Internet
Author: User
Tags integer numbers

Let's start with an example:

x=1+1echo $x

Are you expecting output 2? Let you down. The output result is 1 + 1. Why? This is because the variable type in shell script is "string" by default, so if the variable type is not specified, 1 + 1 is a "string" instead of a "formula ". So how can we get the desired results? There are many methods, but there are two in summary. One is the type of the Life variable. The other is to process a specific computing formula.

1) First, let's look at the first method: declare the type of the variable.

I made the following changes to the above program:

declare -i xx=1+1echo $x

In the above script, I declare X as an integer, and the output result is 2.

Or you can write:

declare -i xdeclare -i yx=1y=2x=$x+$yecho $x

The output result is 3. If the X and Y types are not declared as integer numbers, the output result is 1 + 2.

2)

A) use the let command: (Note that let only supports integer operations)

let 'x=1+1'echo $x

The output result is 2.

B) use $ []

x=1y=2x=$[ x+y]echo $x

Output result: 3

Note the following:

  • $ [] Use the expression in brackets as a mathematical operation to calculate the result and then output it.
  • It doesn't matter if you do not add $ when accessing the variables in $ [].
  • $ [] Supports the same operators as let, but only integer operations.

C) use $ (())

x=1y=2x=$(( x+y))echo $x

The output result is 3.


Related Article

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: info-contact@alibabacloud.com 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.