3. 条件判断
- 格式 [ 表达式 ]
- 表达式前后各有一个空格
- -e:(exist)目标是否存在
- -d:(directory)是否为文件夹
- -f:(file)是否为文件
- 1.判断当前目录下的 1.txt 是否存在,是则输出true[ -e 1.txt ]&& echo "true"
- 2.判断dir1是否是目录,是则输出true[ -d dir1 ]&& echo "true"
- 3.判断1.txt是否为文件,是则输出true[ -f 1.txt ]&& echo "true"
- 4.如果1.txt不存在则创建一个1.txt[ -e 1.txt ] || touch 1.txt
- -r:(read)是否具有读取权限
- -w:(write)是否具有写入权限
- -x:(excute)是否具有运行权限
- 1.判断1.txt 是否具有写权限,有则输出success[ -w 1.txt ]&& echo "success"
- 2.判断1.txt 是否具有读权限[ -r 1.txt ]
- 3.判断1.txt 是否具有执行权限[ -x 1.txt ]
- -eq:(equal) 等于
- -ne:(not equal) 不等于
- -gt:(greater than) 大于
- -lt:(lesser than) 小于
- -ge:(greater or equal) 大于等于
- -le:(lesser or equal) 小于等于
# 1>2
[ 1 -gt 2 ]
# 1<3
[ 1 -lt 3 ]
# 1<=4
[ 1 -le 4 ]
# 4>=3
[ 4 -ge 3 ]
# 1=2
[ 1 -eq 2 ]
# 2!=3
[ 2 -ne 3 ]
- = :相等
- != :不相等
- -z :判断字符串长度是否为0
- -n :判断字符串长度是否不为0
- $ :判断字符串是否不为空
# "hello" 与 "hello"比较
[ "hello" = "hello" ]
[ "hello" != "hello" ]
demo2
# 代码
a="abc"
b="efg"
if [ $a = $b ]
then
echo "equal"
fi
if [ $a != $b ]
then
echo "not equal"
fi
if [ -z $a ]
then
echo "zero"
fi
if [ -n $a ]
then
echo "not zero"
fi
if [ $a ]
then
echo "not empty"
fi
# 输出
not equal
not zero
not empty
利用bc计算器比较
- 满足返回 1
- 不满足返回 0
5 是否 大于 1.3
[ `echo "5>1.3"| bc` -eq 1 ]
- || :或
- && :且
- ! :非
- -o :或
- -a :且例子```basha=123b=456c=123if [[ $a -eq $c || $a -lt $b ]]thenecho "a = c 或 a < b"fi
if [[ $a -eq $c && $b -gt $a ]] then echo "a = c 且 b > a" fi
if [[ ! $a -ne $c ]] then echo "a = c" fi
if [ $a -eq $c -o $a -lt $b ] then echo "a = c 或 a < b" fi
if [ $a -eq $c -a $b -gt $a ] then echo "a = c 且 b > a" fi ```
Last modified 3yr ago