0
点赞
收藏
分享

微信扫一扫

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

卿卿如梦 2022-02-19 阅读 69

文章目录

基本运算符

算数运算符

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
举报

相关推荐

0 条评论