[Shell Foundation]--arithmetic operations

Source: Internet
Author: User
Tags arithmetic bitwise

The shell supports only integer operations. Typically let, expr, declare, $[] are implemented.

More accurate calculations suggest using the BC tools under Linux-a high-precision computing language.

1. let is a shell built-in integer operation command

# # can be completed +-*/% * * Subtraction Yu Yu and other general operatorsLet a=1+1;Echo$alet b=9/4;Echo$blet C=Ten%3;Echo$clet D=a**3;Echo$d
# # = = = *=/=%= and other mixed operators can be completed
X=8; let x-=2 Echo$xy=8; let y/=2 Echo$y # Bash let.SH2218

# # Shift Operation
n=4Echo "obase=2; $n"|BC #输出一个数的二进制let"val1= $n <<2"Echo "obase=2; $val 1"| BC;Echo$val 1let"val2= $n >>2"Echo "obase=2; $val 2"| bcEcho$val a bash let.SH -10000 -11

# #按位与, bitwise OR, bitwise NON, bitwise XOR, or arithmetic
n1=8N2=4Echo-N"N1:";Echo "obase=2; $n 1"|BCEcho-N"N2:";Echo "obase=2; $n 2"|Bclet"value= $n 1| $n 2"Echo-N"| or operation:";Echo "obase=2; $value"|Bclet"value= $n 1& $n 2"Echo-N"& and Operations:";Echo "obase=2; $value"|Bclet"value= $n 1^ $n 2"Echo-N"^ xor operation:";Echo "obase=2; $value"|bc# bash let.SHN1: +N2: -| or operation:1100& and Operations:0^ XOR Operation:1100

# # self-increment self-subtraction operation
n1=TenN2=Ten Let"result_1= (++N1)"#先自增再赋值 #注意此时里面的n1并没有写成 $n 1
Let"result_2= (n2++)"#先赋值再自增Echo "n1= $n 1"Echo "n2= $n 2"Echo "result_1= $result _1"Echo "result_2= $result _2"#bash let.SH One One OneTen

2. Other operators $[], expr, declare

Echo$[1+1]Echo$[5/2]Echo$[2**3]Expr 2\*2 #注意操作数运算符的空格; and the escape of the operatorDeclare-I JJ=1+1Echo$J #bash test.SH22842

3. Arithmetic Expression $ ((arithmetic expression))

i=2echo $ ((2*i+1))Echo $ ((2* (i+1))  #可以用括号表达先计算括号里的式子 #bash test. SH 5 6

4. BC Tools (more commonly used)

Echo " 3^2 " | BC   #注意怎么写 echo"scale=3;10/3" | BC  #scale =n means to reserve N as decimal #bash test. SH 9 3.333

[Shell Foundation]--arithmetic operations

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.