示例1:进行简单的数值计算:
[root@vm1 scripts]# ((i=5))
[root@vm1 scripts]# ((i=i**2))
[root@vm1 scripts]# echo $i
25[root@vm1 scripts]# echo 6-3
6-3
[root@vm1 scripts]# echo $((6-3))
3
说明:
如果需要输出,就要加$符号。
示例2:综合算术运算:
[root@vm1 scripts]# ((a=1+2**3-4%3))
[root@vm1 scripts]# echo $a
8
示例3:特殊运算符号:
[root@vm1 scripts]# a=8
[root@vm1 scripts]# echo $((a=a+1))
9
[root@vm1 scripts]# echo $((a+=1))
10
[root@vm1 scripts]# echo $((100*(100+1)/2))
5050
示例4:比较判断:
[root@vm1 scripts]# echo $((3<8))
1
[root@vm1 scripts]# echo $((3>8))
0
[root@vm1 scripts]# echo $((8==8))
1
[root@vm1 scripts]# echo $((7!=9))
1[root@vm1 scripts]# if ((8>7 && 5==5));then echo yes;fi
yes
上面所涉及到了数字和变量必须为整数(整型)。不能为小数(浮点数)或者字符串。
示例5:echo $((a++)) echo $((a--)) echo $$((++a)) echo $((--a))
变量在运算符之前,输出表达式的值为a,然后a再进行自增或自减。
变量在运算符之后,先进行自增或自减,然后再输出表达式的值。
这个比较简单,跟C语言一样。
示例6:通过(()) 运算后赋值给变量。
[root@vm1 scripts]# myvar=99
[root@vm1 scripts]# echo $((myvar+1))
100
[root@vm1 scripts]# echo $(( myvar + 1 ))
100
[root@vm1 scripts]# echo $(( myvar + 1 ))
100
[root@vm1 scripts]# myvar=$((myvar+1))
[root@vm1 scripts]# echo $myvar
100
说明:(())里面的所有字符之间没有空格,有一个或者多个空格都不会影响结果。
然后我们看一个例子:
[root@vm1 scripts]# cat jisuan1.sh
#!/bin/bash
#
print_usage(){printf "Please enter an integer\n"exit 1
}read -p "Please input first number: " firstnumif [ -n "`echo $firstnum|sed 's/[0-9]//g'`" ];thenprint_usage
firead -p "Please input the operator: " operatorif [ "$operator" != "+" ] && [ "$operator" != "-" ] && [ "$operator" != "*" ] && [ "$operator" != "/" ];thenecho "Please use {+|-|*|/}"exit 2
firead -p "Please input second number: " secondnumif [ -n "`echo $second|sed 's/[0-9]//g'`" ];thenprint_usage
fiecho "${firstnum}${operator}${secondnum}=$((${firstnum}${operator}${secondnum}))"
代码说明:
1)sed 's/[0-9]//g': 遇到数字就替换为空,表示将数字字符都进行删除。
2)删除读入内容的数字部分看是否为空,-n功能。进而判断读入的内容是否为整数。
3)我们也使用了函数print_usage
4)exit <value>: 表示出现错误。
5)(())就是进行计算。${}使用大括号,避免出现“金庸新著”的问题。
[root@vm1 scripts]# cat jisuan2.sh
#!/bin/bash
#
print_usage(){printf "USAGE: $0 NUM1 {+|-|*|/} NUM2\n"exit 1
}if [ $# -ne 3 ];thenprint_usage
fifirstnum=$1
op=$2
secondnum=$3if [ -n "`echo $firstnum | sed 's/[0-9]//g'`" ];thenprint_usage
fiif [ "$op" != "+" ]&&[ "$op" != "-" ]&&[ "$op" != "*" ]&&[ "$op" != "/" ];thenprint_usage
fiif [ -n "`echo $secondnum | sed 's/[0-9]//g'`" ];thenprint_usage
fiecho "${firstnum}${op}${secondnum}=$((${firstnum}${op}${secondnum}))"
代码说明:
1)使用的是传参的方式。
2)判断的内容跟上面基本上是一样的。
3)注意下print_usage函数中的 $0,表示脚本进程的名称。在工作中这个要用起来。
老师的一个简单的例子:
[root@vm1 scripts]# cat bc.sh
echo $(($1$2$3))
[root@vm1 scripts]# sh bc.sh 1*10
10
[root@vm1 scripts]# sh bc.sh 15*12
180
[root@vm1 scripts]# sh bc.sh 2**5
32
看看这个例子比较简单。
但是需要对输入进行一些判断。