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