您的位置:首页 > 运维架构 > Shell

shell-变量的数值计算2

2017-01-07 17:16 609 查看
let命令的用法
[root@localhost shell]# i=2
[root@localhost shell]# let i=i+8
[root@localhost shell]# echo $i
10
[root@localhost shell]# i=i+8
[root@localhost shell]# echo $i
10+8
[root@localhost shell]#
从上面可以看出如果没有用let的话,是不会计算的,就把我们的计算公式看成一个字符串来用
expr命令的用法

expr命令一般用于整数值,但也可用于字符串,用来求表达式变量的值,同时expr也是一个手工命令行计算器也就是说它自己本身就有计算功能的,如图
[root@localhost shell]# expr 2 - 2
0
[root@localhost shell]# expr 2 + 2
4
[root@localhost shell]# expr 2 \* 2
4
[root@localhost shell]# expr 2 \/ 2
1
[root@localhost shell]# expr 2 \% 2
0
[root@localhost shell]#

一般在shell里面的用法也是这样的

[root@localhost shell]# result="$(expr 3 + 4)"
[root@localhost shell]# echo $result
7
注意:运算符左右都有空格的,使用符号的时候最好给反斜线屏蔽其特定含义

在循环中可用于增量计算,不过一般我们用let命令,如果你用[]的话可以不用空括号

[root@localhost shell]# expr $[2+3]
5
[root@localhost shell]# expr $[4+5]
9
expr可以用来判断某个文件是不是某个后缀的,如
[root@localhost shell]# expr "id_dsa.pub" : ".*.pub"
10
如果是pub后缀就会输出这个文件名字符串的长度。如果不是的话就会输出0
可以判断变量是否为整数,如图

[root@localhost shell]# cat compute.sh
#!/bin/bash
read -p "please input:" a
expr $a + 0 &>/dev/null
[ $? -eq 0 ] && echo int || echo chars
[root@localhost shell]# sh compute.sh
please input:a
chars
[root@localhost shell]# sh compute.sh
please input:1
int
[root@localhost shell]#
bc命令的用法

bc是unix下的计算器,它也可以用在命令行下面,bc支持科学计算,所以经常用,一般的用法如下
[root@localhost shell]# echo 5.1+5|bc
10.1
[root@localhost shell]# echo 5.1+10|bc
15.1
[root@localhost shell]# seq -s "+" 100|bc
5050
[root@localhost shell]#
scale是指保留小数点后几位
obase是把十进制转换为二进制
[root@localhost shell]# echo "scale=2;5.23/3.13"|bc
1.67
[root@localhost shell]# echo "scale=3;5.23/3.13"|bc
1.670
[root@localhost shell]# echo "obase=2;8"|bc
1000
bc的特点是支持小数运算。

可以看看著名的杨辉三角(主要看第一种就可以啦) http://oldboy.blog.51cto.com/2561410/756234
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  expr bc