shell使用笔记-算术运算

一、Bash 内置命令

1. declare / typeset 整数运算

-i     The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION above) is performed  when the variable is assigned a value.

declare -i x=4+2
echo $x
6

declare -i x=4-2
echo $x
2

declare -i x=4*2
echo $x
8

declare -i x=4/2
echo $x
2

declare -i x=2**4
echo $x
16
typeset -i x=4+2
echo $x
6

typeset -i x=4-2
echo $x
2

typeset -i x=4*2
echo $x
8

typeset -i x=4/2
echo $x
2

typeset -i x=2**4
echo $x
16

2. let

let arg [arg ...]
              Each arg is an arithmetic expression to be evaluated (see ARITH‐
              METIC  EVALUATION  above).   If the last arg evaluates to 0, let
              returns 1; 0 is returned otherwise.

let x=4+2
echo $x
6

let x=4-2
echo $x
2

let x=4*2
echo $x
8

let x=4/2
echo $x
2

let x=4**2
echo $x
16

3. Arithmetic Expansion 算术展开

echo $((x=4+2))
6
echo $x
6

echo $((x=4-2))
2
echo $x
2

echo $((x=4*2))
8
echo $x
8

echo $((x=4/2))
2
echo $x
2

echo $((x=4**2))
16
echo $x
16
echo $[x=4+2]
6
echo $x
6

echo $[x=4-2]
2
echo $x
2

echo $[x=4*2]
8
echo $x
8

echo $[x=4/2]
2
echo $x
2

echo $[x=4**2]
16
echo $x
16

3. = 自然运算 SIMPLE COMMAND EXPANSION

x=4+2
echo $x
6

x=4-2
echo $x
2

x=4*2
echo $x
8

x=4/2
echo $x
2

x=2**4
echo $x
16

 

二、 expr

expr - evaluate expressions 计算表达式的值

expr 4 + 2
6

expr 4 - 2
2

expr 4 \* 2
8

expr 4 / 2
2

三、bc

bc - An arbitrary precision calculator language

echo "4+2" | bc
6

echo "4-2" | bc
2

echo "4*2" | bc
8

echo "4/2" | bc
2

echo "4^2" | bc
16

echo "sqrt(4)" | bc
2

echo "c(90)" | bc --mathlib
-.44807361612917015236

echo "s(90)" | bc --mathlib
.89399666360055789051

交互模式

bc --mathlib

bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
4+2
6
4-2
2
4*2
8
4/2
2.00000000000000000000
4^2
16
sqrt(4)
2.00000000000000000000
c(60)
-.95241298041515629269
c(30)
.15425144988758405071
c(45)
.52532198881772969604
c(90)
-.44807361612917015236
s(30)
-.98803162409286178998


[1] http://blog.csdn.net/taijianyu/article/details/6907288

[2] https://wiki.bash-hackers.org/syntax/ccmd/arithmetic_eval

[3] https://wiki.bash-hackers.org/syntax/arith_expr

[4] https://wiki.bash-hackers.org/syntax/expansion/arith

[5] man expr

[6] man let

[7] man bash

[8] man bc

[9] https://www.cnblogs.com/Scott007/p/3263691.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值