算数运算符
算数运算符 + - * / % = == !=,可使用expr 表达式进行求值操作
#!/bin/bash
val=`expr 2 + 2`
echo "两数之和:$val"
a=10
b=20
val=`expr $a + $b`
echo "两数相加:$val"
val=`expr $a - $b`
echo "两数相减:$val"
val=`expr $b / $a`
echo "两数相除:$val"
# 乘号(*)前边必须加反斜杠(\)转义才能实现乘法运算
val=`expr $b \* $a`
echo "两数相乘:$val"
val=`expr $a % $b`
echo "a与b取余 :$val"
# 条件表达式要放在方括号之间,并且要有空格
if [ $a == $b ]
then
echo "a == b"
fi
if [ $a != $b ]
then
echo "a != b"
fi
:<<!
两数之和:4
两数相加:30
两数相减:-10
两数相除:2
两数相乘:200
a与b取余 :10
a != b
!
关系运算符
-eq:等于
-ne:不等于
-gt:大于
-lt:小于
-ge:大于等于
-le:小于等于
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b a == b"
else
echo "$a -eq $b a != b"
fi
if [ $a -ne $b ]
then
echo "$a -ne $b a != b"
else
echo "$a -ne $b a == b"
fi
if [ $a -gt $b ]
then
echo "$a -gt $b a > b"
else
echo "$a -gt $b a < b"
fi
:<<!
10 -eq 20 a != b
10 -ne 20 a != b
10 -gt 20 a < b
!
布尔运算符
!: 非运算
-o: 或运算
-a: 与运算
a=11
b=12
if [ $a -gt 1 -o $b -gt $a ]
then
echo "b == $b"
else
echo "a == $a"
fi
:<<!
b == 12
!
逻辑运算符
&& 逻辑and
|| 逻辑or
a=12
b=13
if [[ $a -lt 100 && $b -gt 100 ]]
then
echo "返回 true"
else
echo "返回 false"
fi
if [[ $a -lt 100 || $b -gt 100 ]]
then
echo "返回 true"
else
echo "返回 false"
fi
:>>!
返回 false
返回 true
!
字符串运算符
=: 检测两个字符串是否相等
!=: 检测两个字符串是否不相等
-z: 检测字符串长度是否为0
-n: 检测字符串长度是否不为0
$: 检测字符串是否为空
if [ "aaa" = "bbb" ]
then
echo "aaa == bbb "
else
echo "aaa != bbb"
fi
if [ "aaa" != "bbb" ]
then
echo "aaa != bbb"
else
echo "aaa == bbb"
fi
a="aaaa"
if [ -z $a ]
then
echo "-z $a : 字符串长度为 0"
else
echo "-z $a : 字符串长度不为 0"
fi
if [ -n $a ]
then
echo "-n $a: 字符串长度不为0"
else
echo "-n $a: 字符串长度为0"
fi
if [ $ ]
then
echo " $ '' : 检测字符串为空"
else
echo "$ 检测字符串不为空"
fi
文件测试运算符
-d: 检测文件是否是目录
-f:检测文件是否是普通文件
-r: 检测文件是否可读
-w: 检测文件是否可写
-x: 检测文件是否可执行
-s: 检测文件是否为空
-e: 检测文件是否包含目录
#!/bin/bash
filename="$0"
# filename="/var/www/runoob/test.sh"
echo "打印文件名:$filename"
if [ -d $filename ]
then
echo "这是目录"
else
echo "这不是目录"
fi
if [ -f $filename ]
then
echo "this is ordinary file"
else
echo "this is not ordinary file"
fi
if [ -r $filename ]
then
echo "file is readable"
else
echo "file is unreadable"
fi
if [ -w $filename ]
then
echo "file is writable"
else
echo "file is not writable"
fi
if [ -x $filename ]
then
echo "file is executable"
else
sudo chmod +x $filename
ls -l $filename
fi
if [ -s "$filename" ]
then
echo "file is not empty"
else
echo "file is empty"
fi
if [ -e "$filename" ]
then
echo "There are directories for files"
else
echo "There are no directories for files"
fi