首页 > 系统 > Linux > 正文

Linux Shell脚本系列教程(五):数学运算

2019-10-26 18:46:22
字体:
来源:转载
供稿:网友

在任何一种编程语言中,算术运算都是必不可少的,shell也不例外。

一、 使用let、(())和[]进行算术运算

可以使用普通变量赋值方法定义数值,这是,它会被保存为字符串。我们可以通过使用let、(())、[]等操作符,使得这些变量进行算术运算。例如:
代码如下:
#!/bin/bash
no1=4                        #此处no1义字符串形式存储
no2=5                        #此处no2义字符串形式存储
let result=no1+no2          
echo $result                 #输出结果为 9
let no1++                    #等价于 let no1=no1+1
echo $no1                    #输出结果为5
let no2--                    #等价于 let no2=no2-1
echo $no2                    #输出结果为 4
let no1+=5                   #等价于 let no1=no1+5
echo $no1                    #输出结果为10
let no1-=5                   #等价于 let no1=no1-5
echo $no1                    #输出结果为 5

no1=4                        #此处no1义字符串形式存储
no2=5                        #此处no2义字符串形式存储
result=$[ no1 + no2 ]
echo $result                 #输出结果为9
result=$[ $no1 + 5 ]         #ubuntu中不能正常运行,no1 not found
echo $result                 #输出结果为9
result=$(( no1 + 50 ))       #括号前的$不可丢失,否则报错

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表