[Note]shell programming: mathematical calculations

Source: Internet
Author: User
Tags arithmetic

In shell script, there are several ways to do math, although a few of the results are similar, in writing a program is enough to use a method, but we may also need to learn other people's program Ah, in the reading of other people's programs can not know these things. So, leave a note.


A. expr Command -expr allows mathematical expressions to be processed on the command line, but is slightly clumsy.

Example: $ expr 1 + 5 #注意在表达式中要有空格, if written 1+5 then the result is not what we want.

The expr command recognizes a number of different math and string operators:

Operator Describe
Arg1 | Arg2

Returns ARG1 if no parameter is null or 0; arg2

Arg1 & Arg2

Returns ARG1 if no parameter is null or 0, otherwise 0

Arg1 < Arg2 Returns 0 if Arg1 is less than arg2 returns 1;
Arg1 <= arg2 Arg1 is less than or equal to ARG2 returns 1, otherwise returns 0
Arg1 = arg2 Arg1 equals arg2 returns 1, otherwise returns 0
Arg1! = arg2

Arg1 Not equal to ARG2 returns 1, otherwise returns 0

Arg1 >= arg2

Arg1 is greater than or equal to ARG2 returns 1, otherwise returns 0

Arg1 > Arg2

Arg1 greater than arg2 returns 1, otherwise returns 0

Arg1 + arg2 Returns two-argument arithmetic and
Arg1-arg2 return arithmetic Difference
Arg1 * arg2 Returns the arithmetic product
Arg1/arg2 Return to arithmetic quotient
Arg1% arg2 Returns the remainder of a two number divide
String:regexp If regexp matches a pattern in a string, the pattern is returned
Match String:regexp If regexp matches a pattern in a string, the pattern is returned
substr STRING POS LENGTH Returns a substring with a length of zero at the starting position of the POS
Index STRING CHARS Returns the position of the chars found in string, otherwise 0
Length STRING Returns the length of a string
+ TOKEN The token is interpreted as a string, even if it is a keyword
(EXPRESSION) Returns the value of expression

Note : You may want to use ' \ ' escape or ' escape ' when using the expr command: Expr 2 * 5 ==> expr: syntax error

Expr 2 \* 5 or Expr 2 ' * ' 5 ==>10


two . dollar sign + square brackets --$[operation]

Example: Var1=$[1+5]; ==> var1=6

var2=$[$var 1*3]; ==> var2=18;

This is much more convenient than the previous one ...

Cons: Only integer operations are possible, which is why the bash shell is said to support floating-point arithmetic. I haven't verified it yet.

Statement: Var1=$[100/30] ==> var1=3, if you want to make a floating-point operation you can use the BC calculator. The usage will be described later.


three. dollar sign + double brackets --$ ((operation))

Use the same method as $[].

Example: var=$ ((1+3)) ==> var=4


four . Double Brackets --((expression)) double parenthesis allows you to put advanced mathematical expressions into comparisons and also supports mathematical calculations.

The expression here can be any mathematical assignment or comparison expression, can be a comparison expression, that is, can be used as a test command, in the if and for until structure can be used as a conditional discriminant statement.

val++ (after) self-increment
val--

(after) self-reduction

++val (ex) Self-increment
--val (ex) Self-reduction
Logical negation
~ Bit negation
** Power operation
<< Left shift
>> Right shift
& Bit and
| Bit or
&& Logic and
|| Logical OR

Example: var1=10; ((var2= $var 1**3)); ==> the meaning of the sentence is var2=10*10*10=1000, (10 cubic)

if (($var 1**2>90)); then echo "OK"; Fi ==> when Var1 squared is greater than 90 o'clock output OK.

This thing is very powerful, and it's very intuitive to use in scripts, and when we see (()), we know that there is a numerical calculation.


Five. let command--similar to (());

$let "$var +=1" or $let "var= $var +1";


six. the BC calculator (Big Boss) solves the common scheme of floating-point arithmetic.

(i) using BC at the command line

BC is the first few commands we learn when we learn Linux. Input BC directly on the command line can enter the BC calculator interface, you can define variables inside, calculate expressions and other operations.

For example: $BC

2+5

7

The floating-point operation of the BC calculator is controlled by a variable called scale, in fact, the value of scale=0 is the number of digits after the decimal point, and the BC default, so you need to modify the scale when calculating, such as scale=4, keep the decimal point four.

For example: $BC

3.44/5

0

Scale=4

3.44/5

.6880

You can use the-Q parameter to mask the copyright description that is exported after you enter BC. Quit BC with quit

For example: $BC

Quit

(ii) Use of BC in scripts

BC can accept standard input, and this standard input can be supplied to it by pipeline or redirection.

After BC accepts the standard input, computes the input expression and outputs it to the standard output, we can get its output by $ (COMMAMD) or ' command '.

Common usage One:

variable=$ (echo "options; Expression "| BC);

For example:

Var=$ (echo "scale=4; 3.44/5; "|  BC); ==> var=.6880

Common usage II: redirect with inline (inline) input <<

variable=$ (BC << EOF

Options

statements;

Expressions

EOF)

For example:

var=$ (BC << EOF

scale=4;

var1=20;

var2=3.1415926;

a1= ($var 1 * $var 2);

B1 = ($var 1/$var 2);

A1 + B1;

EOF)

There are many uses, such as file redirection, and the principle is the same.

Temporarily think so much, welcome to add!

This article is from the "Mr_cinus" blog, make sure to keep this source http://cinus.blog.51cto.com/9624650/1581695

[Note]shell programming: mathematical calculations

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.