Bash脚本编程指北(5)基本运算符

基本运算符

算数运算符

vim test.sh
#!/bin/bash

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a == b"
fi
if [ $a != $b ]
then
   echo "a != b"
fi

运行

bash test.sh

a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a != b

TIPS

原生 bash 不支持简单的数学运算,但是可以通过其他命令来实现,例如 awkexprexpr 最常用。

expr 是一款表达式计算工具,使用它能完成表达式的求值操作,注意使用的反引号(esc 键下边)

表达式和运算符之间要有空格, $a + $b 写成 $a+$b 不行

条件表达式要放在方括号之间,并且要有空格 [ $a == $b ] 写成 [$a==$b] 不行

乘号(*)前边必须加反斜杠(\)才能实现乘法运算

关系运算符

关系运算符只支持数字,不支持字符串,除非字符串的值是数字。

实例

vim test2.sh
#!/bin/bash

a=10
b=20

if [ $a -eq $b ]
then
   echo "$a -eq $b : a == b"
else
   echo "$a -eq $b: a != b"
fi

运行

bash test2.sh

10 -eq 20: a != b

逻辑运算符

实例

#!/bin/bash
a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

结果

return false
return true

字符串运算符

#!/bin/bash

a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a == b"
else
   echo "$a = $b: a != b"
fi
if [ -n $a ]
then
   echo "-n $a : The string length is not 0"
else
   echo "-n $a : The string length is  0"
fi
if [ $a ]
then
   echo "$a : The string is not empty"
else
   echo "$a : The string is empty"
fi

结果

abc = efg: a != b
-n abc : The string length is not 0
abc : The string is not empty

文件测试运算符

实例:

#!/bin/bash

file="/home/shiyanlou/test.sh"
if [ -r $file ]
then
   echo "The file is readable"
else
   echo "The file is not readable"
fi
if [ -e $file ]
then
   echo "File exists"
else
   echo "File not exists"
fi

结果

The file is readable
File exists

浮点运算

浮点运算,比如实现求圆的面积和周长。

expr 只能用于整数计算,可以使用 bc 或者 awk 进行浮点数运算。

#!/bin/bash

radius=2.4

pi=3.14159

girth=$(echo "scale=4; 3.14 * 2 * $radius" | bc)

area=$(echo "scale=4; 3.14 * $radius * $radius" | bc)

echo "girth=$girth"

echo "area=$area"

以上代码如果想在环境中运行,需要先安装 bc

sudo apt-get update
sudo apt-get install bc
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海岸星的清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值