shell脚本介绍与基本使用(三)

运算符

​ 例:

​ num1=11

​ num2=22

​ sum=num1+num2

​ echo $sum

​ 格式:expr m + n 或 $((m+n)) (注意expr运算符之间要有空格)

​ expr命令:对整数型变量进行算数运算 (注意运算符前后必须有空格)

​ expr 3 + 5

​ expr 3 - 5

​ echo ‘expr 10 / 3’

​ 10/3的结果是3,因为是取整

​ expr 3 \* 10 # \ 是转义符

​ 例:计算(2+3)× 4 的值

​ 1.分步计算

​ S=‘expr 2 + 3’

​ expr $S \* 4

​ 2.一步完成计算

​ expr 'expr 2+3 ’ \* 4

​ S=‘expr \‘expor 2 + 3\’ \* 4’

​ echo $S

​ 或

​ echo $((2 + 3) * 4))

( ) ()与 {}的区别
$()的用户和反引号’‘一样,用来表示优先执行的命令
eg:echo $(ls a.txt)
就是取变量了eg:echo{PATH}
$((运算内容))适用于数值计算
eg:echo $((3 + 1 * 4))

内置test命令

​ 内置test命令常用于操作符号[]表示,将表达式写在[]中,如下:

​ [ expression ]

​ 或者

​ test expression

​ 注意:expression首尾都有个空格

​ eg:[ ];echo $?

​ 测试范围:整数、字符串、文件

​ 表达式的结果为真,则test的返回值为0,否则为非0。当表达式的结果为真时,则变量$?的值就为0,否则为非0

字符串测试

​ test str1 == str2 测试字符串是否相等

​ test str1 != str2 测试字符串是否不相等

​ test str1 测试字符串是否不为空,不为空,true

​ test -n str1 测试字符串是否不为空

​ test -z str1 测试字符串是否为空

​ eg:

​ name=wtt

​ ["$name"] && echo ok

​ ;命令连接符号

​ && 逻辑与条件满足 才执行后面的语句

​ [ -z “$name” ] && echo invalid || echo ok

​ || 逻辑或,条件不满足,才执行后面的语句

​ test “$name” == “waa” && echo ok || echo invalid

整数测试

​ test int1 -eq int2 测试整数能否相等 equals

​ test int1 -ge int2 测试int1是否>=int2

​ test int1 -gt int2 测试int1是否>int2

​ test int1 -le int2 测试int1是否<=int2

​ test int1 -lt int2 测试int1是否<int2

​ test int1 -ne int2 测试整数是否不相等

​ eg:

​ test 100 -gt 100

​ test 100 -ge 100

​ 如下示例两个变量值的大小比较:

img

文件测试

​ test -d file 指定文件是否目录

​ test -e file 文件是否存在exists

​ test -f file 指定文件是否常规文件

​ test -L file 文件存在并且是一个符号链接

​ test -r file 指定文件是否可读

​ test -w file 指定文件是否可写

​ test -x file 指定文件是否可执行

​ eg:​

​ test -d install.log

​ test -r install.log

​ test -f xx.log ;echo $?

​ [ -L service.soft ] && echo “is a link”

​ test -L /bin/sh ;echo $?

​ [ -f /root ] && echo “yes” || echo “no”

多重条件测试:

​ 条件1 -a 条件2 逻辑与 两个都成立,则为真

​ 条件1 -o 条件2 逻辑或 只要有一个为真,则为真

​ !条件 逻辑非 取反

​ eg:

​ num=520

​ [ -n “num”-a"num" -ge 520] && echo “marry you” || echo “go on”

​ age=20

​ pathname=outlog

​ [ ! -d “$ pathname” ] && echo usable || echo used

发布了104 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/WangTaoTao_/article/details/104969015
今日推荐