变量的数值计算
1.$((表达式))
(1).实验1
[[email protected]~_~ day4]# cat test.sh
#!/bin/bash
a=6
b=2
echo "a-b=$(($a-$b))"
echo "a+b=$(($a+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a%b=$(($a%$b))"
echo "a**b=$(($a**$b))"
[[email protected]~_~ day4]# sh test.sh
a-b=4
a+b=8
a*b=12
a/b=3
a%b=0
a**b=36
(2).实验2
[[email protected]~_~ day4]# cat test2.sh
#!/bin/bash
echo $(($1$2$3))
[[email protected]~_~ day4]# sh test2.sh 1 + 2
3
注意:”1 + 2”有空格,如无则只传给$1
2. $[表达式]
[[email protected]~_~ day4]# echo $[3+4]
7
3.let赋值表达式
等同与(()),但后者效率高
[[email protected]~_~ day4]# i=10
[[email protected]~_~ day4]# let i=i+1
[[email protected]~_~ day4]# echo $i
11
4.expr表达式
注意:运算符及计算的数值左右均有空格
(1).四则运算
[[email protected]~_~ day4]# cat expr.sh
#!/bin/bash
a=$1
b=$2
echo "a*b=`expr $a + $b`"
echo "a-b=`expr $a \* $b`"
[[email protected]~_~ day4]# sh expr.sh 2 3
a*b=5
a-b=6
(2).判断文件拓展名
运用:ssh-copy-id文件中;(vim `which ssh-copy-id`)
用法:
[[email protected]~_~ ~]# cat exprfile.sh
#!/bin/bash
if expr "$1" : ".*\.pub" ;then
echo "is .pub file"
else
echo "is not *.pub file"
fi
[[email protected]~_~ ~]# sh exprfile.sh test.pub
8
is .pub file
[[email protected]~_~ ~]# sh exprfile.sh test.pu
0
Is not *.pub file
(3).判断一个数是否为整数
[[email protected]~_~ day4]# cat isInteger.sh
#!/bin/bash
expr $1 + 1 &>/dev/null
if [ $? -eq 0 ]
then
echo "Is Integer"
else
echo "Is not a Integer"
fi
[[email protected]~_~ day4]# sh isInteger.sh 3.9
Is not a Integer
[[email protected]~_~ day4]# sh isInteger.sh 3
Is Integer
(4).计算字符串长度
[[email protected]~_~ day4]# echo `expr length "Hello"`
5
还有其他运用,查看man expr
5.bc命令
一个计算器,用yum安装;直接bc进入计算器; 支持浮点数计算.
(1).交互环境
[[email protected]~_~ day4]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty‘.
2*3
6
3+7+5
15
3.4+5.6
9.0
(2).加管道符
[[email protected]~_~ day4]# echo "3+5"|bc
8
(3).通过scale指定计算精度
[[email protected]~_~ day4]# var=3.14
[[email protected]~_~ day4]# var=`echo "scale=2;$var*3"|bc`
[[email protected]~_~ day4]# echo $var
9.42
6.awk命令进行计算
支持浮点运算,内置有log、sqr、cos、sin等等函数
[[email protected]~_~ day4]# var=`echo "$var"|awk ‘{printf("%g",sin($1))}‘`
[[email protected]~_~ day4]# echo $var
0.841471
[[email protected]~_~ day4]# var=`echo "$var 2"|awk ‘{printf("%g",cos($1/$2))}‘`
[[email protected]~_~ day4]# echo $var
0.97922