Arithmetic Operators and usage Summary

Source: Internet
Author: User

I. Overview
Arithmetic Operators are operators that can implement mathematical operations such as addition, subtraction, multiplication, and division in a program. The common mathematical operators in shell are as follows.
+: Add two variables.
-: Subtract two variables.
*: Multiply two variables.
/: Divide two variables.
**: Calculate the power of two variables.
%: Modulo operation. Divide the first variable by the second variable to calculate the remainder.
+ =: Add equals, and add the second variable on the basis of itself.
-=: Subtraction equals. Subtract the second variable from the first variable.
* =: Multiplication equals. Multiply the first variable by the second variable.
/=: Divide the Division by the second variable based on the first variable.
% =: Modulo value assignment. The first variable performs the modulo operation on the second variable, and then assigns the value to the first variable.
When using these operators, you must note the order of operation. For example, input the following command to output the result of 1 + 2. Echo 1 + 2
Shell does not output result 3, but outputs 1 + 2. There are three methods in shell to change the operation sequence.
-Use expr to change the operation sequence. Echo 'expr 1 + 2' Can Be Used to output the result of 1 + 2. expr is used to represent the following expression as a mathematical operation. Note that 'is not a single quotation mark, but the symbol above the tab key.
-$ () Indicates a mathematical operation. You can assign the result of an operation to variable B. The operation command is B =$ (1 + 2 )). Then ECHO $ B is used to output the value of B. Output result 3.
-$ [] Indicates a mathematical operation. Write a mathematical operation to the brackets of the $ [] symbol. The content in the brackets performs mathematical operations first. For example, Echo $[1 + 2] will output result 3.

2. Exploration
Replace $ [] and $ () with expressions (())
Expression Operation Command expr
(1) Spaces
$ [] Indicates that the expression in the parentheses of the shell is used to evaluate the value. You can also use $ (())
The space in square brackets of ECHO $[2 + 3] does not affect the understanding of the expression, that is, it can be written as $[2 + 3], $[2 + 3], $[2 + 3], $[5 ** 3], and other Forms

Note the following when using expr:
For example, Echo 'expr 8/2 'only applies spaces in this case. It is also allowed to add spaces on both sides next to the symbol ''.
Return Value: when the expression exits, it is neither null nor 0, and the return value is 0.
If the expression is null or 0, the return value is 1.
When the expression is invalid in syntax (or statement composition), the return value is 2.
If an error occurs in the expression, the returned value is 3.

(2) four consecutive arithmetic operations
$[2 + 4*2/3], $(2*3-5 + 3/2), 'expr 8/2 + 3' is correct
(3) add brackets to change the priority.
$[(2 + 4) * 2-10)/5] parentheses can be used like a normal formula.
$(2*(5-(5 + 3)/2) You can also use parentheses like a normal formula.
But expr cannot be enclosed in parentheses. For example, Echo 'expr (8/2) 'is incorrect. Use 'expr 8 // (2 + 2 /) ', that is, add a backslash before () to escape

(4) The functions of the two formats are the same. All shell evaluate values are completed with integers.
That is, decimal places are not accepted, such as $ [2.5*2] or $ (3.3-2) or expr 2.5*3. Otherwise, a syntax error is returned.

(5) $ [] numbers with different bases
$ [0xa + 071-3] uses the hexadecimal 0xa and 071 of the octal, and the default value is the decimal number 3.
Expr does not accept other hexadecimal numbers. Although the following command 'expr 071 + 3' can be passed and calculated by syntax, the value is 74, that is, 71 of the original intention is to be entered, it is interpreted as a decimal number, but the hexadecimal number directly prompts a syntax error.

(6) All the above operations are performed when constants perform arithmetic operations. The four arithmetic operations on variables are as follows:
Foo = 0;
Foo = 'expr $ Foo + 1'; echo "foo is $ foo ";
Fly = $[3 + 5];
Fly + = $ [$ Foo + 1];
Fly2 = $ ($ Foo + 1 ));
Echo "foo is $ Foo, fly is $ fly, fly2 if $ fly2 ";
It can be seen that both $ [], $ () and expr can operate on variables.
Note 1: no space is allowed between the variables on the left or between the expression on the right and the equal sign. No space is allowed between the combined value assignment symbol of the + = Class and the variable and expression.
NOTE 2: variables included in () do not need to use the dollar sign $, that is, fly2 = $ (FOO + 1); it is also true.
(7) character operations
The biggest difference between expr and $ [] and $ () is that it can accept characters and can process the characters as shown in the following three commands:
Expr AAA: 'A/+'
Expr ABC: 'A/(./) C'
Expr index abcdef CZ
(8) Special Handling of operator numbers
Expr is correct when using multiplication, such as expr 8/* 8, that is, when using shell programming and shell terminal input, a backslash is required to escape the * sign, in order to use the multiplication symbol normally.
There is also a power operator **, even if this form of limit expr 8/* 2 is not working properly, I have not found the correct power Operator Method in the expr, which of the following heroes knows? Please kindly advise me!

(9) floating point calculation
Bash only has basic mathematical computing capabilities and does not support floating-point computing. expr and let both support integer computing. You can use tools such as BC, awk, and Perl to calculate floating point numbers.
The format of BC is variable = $ (echo "options; operations" | BC). The following are several examples:
1. Echo "3.22*4.32" | BC
2. Echo "size = 4; 2.34*6.77" | BC
3. xx = 3.45; YY = $ (echo "$ XX" | BC); echo "The result is $ YY ";
BC, you can also have the-l parameter, indicating that the mathematical library is called, such as a technique. 4; Han. 6; echo "$ S + 0.5 ^ $ I" | BC-l

After summing up, we find that [] is test, and () is let. Below is a summative description of the two:

The test command of the square brackets usually uses the built-in test command to test the expression value. The test command is also linked to the square brackets. In this way, you can use a separate test command or
The expression is enclosed in square brackets to test the value of the expression. When you use the test command or square brackets to test the expression, the shell metacharacters in the expression are not extended. To separate words from variables
The string that contains a blank character must be enclosed in quotation marks.
In bash 2. x, the test command is enclosed in brackets [[
] (The built-in test composite command) is used to test the expression value. The variable is not separated by words, but pattern matching can be performed through the metacharacter extension. Strings that contain blank characters must be enclosed in quotation marks.
. If a string (no matter whether it contains any blank characters) is just a common string in an expression, rather than a part of a pattern, it must also be enclosed in quotation marks. Logical operators &
& (And) and | (OR) Replace the-A and-O options used with the test command.
Although the test command can calculate the value of an arithmetic expression, the reader may prefer the let Command, because the let Command has a variety of class C operators (Bash 2.x ). The let command can contain expressions in a set of parentheses to express different meanings.
Whether the test command, composite command, or let command is used, the expression results will be tested. If the return value is zero, the operation is successful, and if the return value is non-zero, the operation fails.

The compound test operation (parentheses) is mentioned here. The example is as follows:
Varh = "hello"; if [$ varh = "hello"]; then Echo "hi"; else echo "bye"; FI;
Varh = "hello"; if [[$ varh = "hello"]; then Echo "hi"; else echo "bye"; FI;
In this case, the double brackets are synonymous with the single brackets and can be used interchangeably.
However, the following situations cannot be exchanged:
Varh = "hello"; if [[$ varh = [HH] ell? ]; Then Echo "hi"; else echo "bye"; FI;
The brackets can be used for pattern matching. It can enclose metacharacters, that is, you can use metacharacters such *? [] And so on.

Shell programming notes (1)- of variables and operators
Full manual Linux system C program development details
Test and let. Http://

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: 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.