实现算术运算的几种方式
方式一:使用let命令
bash 中可使用 let
命令来完成算术运算,具体使用信息可通过 help let
查看。
let
命令的使用格式如下:
let var=算术表达式
例:
[root@localhost ~]# num1=2
[root@localhost ~]# num2=3
[root@localhost ~]# let sum=$num1+$num2
[root@localhost ~]# echo $sum
5
方式二:使用算数表达式块
bash 中除了可使用 let
命令来实现算数运算外,还可通过指定符号来指定一个算术表达式块,格式如下:
$[算数表达式] 或 $((算数表达式))
例:
[root@localhost ~]# echo $[2+3]
5
[root@localhost ~]# echo $((2+3))
5
方式三:使用expr命令
还可使用 expr
命令,只不过 expr
命令相对上述两种方式来说易读性还是差一些,格式如下:
expr arg1 arg2 arg3
arg1:为操作数 1
arg2:为算数运算符
arg3:为操作数 2
例:
[root@localhost ~]# expr 2 + 3
5
补充
bash内建的随机数变量
bash 中有一个内建的随机数生成器变量 $RANDOM
,例:
[root@localhost ~]# echo $RANDOM
28384
[root@localhost ~]# echo $RANDOM
26328
[root@localhost ~]# echo $RANDOM
8536
$RANDOM
生成的是1-32767
之间的随机数。
练习
1、写一个脚本,计算 /etc/passwd
文件中的第 10 个用户he第 20 个用户的 ID 之和。
编辑脚本 useridsum.sh
内容如下:
#!/bin/bash
userid1=$(head -n 10 /etc/passwd | tail -n 1 | cut -d: -f3)
userid2=$(head -n 20 /etc/passwd | tail -n 1 | cut -d: -f3)
useridsum=$[$userid1+$userid2]
echo "uid sum is $useridsum."
执行:
[root@localhost ~]# ./useridsum.sh
uid sum is 1008.
2、写一个脚本,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和。
编写脚本 spacelinecount.sh
内容如下:
#!/bin/bash
spaceline1=$(grep "^[[:space:]]*" $1 | wc -l)
spaceline2=$(grep "^[[:space:]]*" $2 | wc -l)
echo "The sum of space line: $[$spaceline1+$spaceline2]"
执行:
[root@localhost ~]# ./spacelinecount.sh /etc/passwd /etc/profile
The sum of space line: 105
3、统计 /etc
、/var
、/usr
目录共有多少个一级子目录和文件。
编写脚本 dirfilesum.sh
内容如下:
#!/bin/bash
d_count=`ls -l -a /etc /var /usr | grep -E -o "^d" | wc -l`
f_count=`ls -l -a /etc /var /usr | grep -E -o "^-" | wc -l`
echo "$[$d_count+$f_count]"
测试执行:
[root@localhost ~]# ./dirfilesum.sh
208
评论区