# [] 、[[]]两边都有空格 # 1 if [ 条件表达式 ] then command fi # 2、支持正则 if [[ 条件表达式 ]] then command fi # 3 if test 条件表达式 then command fi #ifelse if [ 条件判断 ] then command else command fi
常用相关参数
文件、文件夹、权限的判断
参数
用途
-e
存在(任何文件,包括目录)
-f
存在且是普通文件
-d
存在且是文件夹
-s
存在且是非空文件夹
-r
存在且可读
-w
存在且可写
-x
存在且可执行
例子:
1 2 3 4 5 6
# 判断是否存在 pwd_path=$(pwd) if [ -e $pwd_path ] then echo $pwd_path fi
整数的判断
参数
用途
-eq
相等(equal)
-ne
不等(not equal)
-gt
大于(greater than)
-lt
小于(less than)
-ge
大于等于
-le
小于等于
1 2 3 4 5 6
if [ 3 -gt 4 ] then echo 3 else echo 4 fi
字符串判断
参数
用途
例子
-z
是否为空,字符串长度为0成立
[ -z ‘lss’ ] # false
-n
是否不为空
[ -n ‘lss’ ] # true
string1 = string2
字符串相等
[ ‘lss’ = lss ] # true
string1 != string2
字符串不相等
[ ‘lss’ != lss ] # false
1 2 3 4 5 6 7
if [ 'text' = text ] then echo "equal" else echo "not equal" fi # equal