Arithmetic Operations in bash

Source: Internet
Author: User

Arithmetic Operations in Bash:

Operators +,-, *,/, and %

Declare:

-I: integer variable

-X: environment variable, similar to export

1. Let: performs arithmetic operations in the format of let varname = arithmetic expression

If the calculation result is decimal, the fractional part is omitted.

For example, let sum = 4 + 1 and the result is 5.

Echo $ sum

Let s = 16/3, the result is 5

Echo $ s

2. varname = $ [arithmetic expression]


3. varname = $ (arithmetic expression ))


4. varname = 'expr $ num1 + $ num2'. Note that there must be spaces before and after +. If not, a hyphen is required.


For example, to write a script, calculate the sum of 1 to 100.

#! /Bin/bash

Declare-I sum = 0;

For num in {1 .. 100}

Do

Let sum = $ sum + $ num

Done

Echo $ sum

For example, write a script to calculate the sum of the odd and even numbers between 1 and 100.

#! /Bin/bash

Delcare-I oddsum = 0, evensum = 0

For I in 'seq 1 2 100'

Do

Let oddsum = $ oddsum + $ I

Done

Echo $ oddsum


For I in 'seq 2 2 100'

Do

Let evensum = $ evensum + $ I

Done

Echo $ evensum

Example: Calculate the sum of all current user IDs

#! /Bin/bash

Declare-I useridsum = 0

For I in 'cut-D: F3/etc/passwd'

Do

Useridsum = $ useridsum + $ I

Done

Echo $ useridsum

For example, calculate the characters of the three files/etc/rc. d/rc. sysinit/etc/init. d/functions/etc/issue.

#! /Bin/bash

Declare-I charsum = 0

For file in/etc/rc. d/rc. sysinit/etc/init. d/functions/etc/issue

Do

Charsum = $ charsum + 'wc-C $ file | cut-d'-f1'

Done

Example: create 10 users, tmpUser1-tmpUser10, and calculate the sum of their IDs

#! /Bin/bash

Declare-I useridsum = 0

For I in {1 .. 10}

Do

Useradd tmpuser $ I

Let useridsum = $ useridsum + 'id-u tmpuser $ I'

Done


Arithmetic Operations in bash

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.