码迷,mamicode.com
首页 > 系统相关 > 详细

shell-变量的数值计算2

时间:2017-01-07 21:24:29      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:expr bc

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

本文出自 “爱周瑜” 博客,请务必保留此出处http://izhouyu.blog.51cto.com/10318932/1890019

shell-变量的数值计算2

标签:expr bc

原文地址:http://izhouyu.blog.51cto.com/10318932/1890019

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!