if语句常用命令选项:
a == b a与b是否相等 (a、b是数值)
a -ge b a 是否大于等于 b
a -gt b a 是否大于 b
a -le b a 是否小于等于 b
a -lt b a 是否小于 b
a -ne b a 是否不等于 b
str1 = str2 str1是否与str2相同(str1、str2是字符串)
str1 != str2 str1是否与str2不同
str1 < str2 str1是否小于str2
str1 > str2 str1是否da于str2
-n str 判断str长度是否非零
-z str str长度是否为0
-d file 判断file是否为目录
-e file 判断file是否存在
-f file 检查file是否为文件
-r file 判断文件是否可读
-s file 判断file是否存在并非空
-w file 判断file是可写
-x file 判断file是可执行
语法:
1,单分支语句结构
if [ 条件表达式 ]; then
指令
fi
2,双分支语句结构
if [ 条件表达式 ]; then
指令一
else
指令二
fi
示例:
#!/bin/bash
a=$1
b=$2
if [ $a == $b ];then
echo "a and b is equal"
else
if [ $a -lt $b ];then
echo "a less than b"
else
echo "a bigger than b"
fi
fi
逻辑运算符运用:
1,&& 表示与
2,||表示或
在[ ]中不能用&& ||
3,[]之间使用逻辑运算符:
-a 与
-o 或
! 非
示例:
if [ $score -ge 0 -a $score -lt 60 ];then
echo "sorry,you are lost!"
elif [ $score -ge 60 -a $score -lt 85 ];then
echo "just soso!"
elif [ $score -le 100 -a $score -ge 85 ];then
echo "good job!"
else
echo "input score is wrong , the range is [0-100]!"
fi
#linux使用if判断文件是否存在
#这里的-f参数判断/home/abc.log是否存在
if [ -f "/home/abc.log" ]; then
echo "文件存在"
else
echo "文件不存在"
fi
更多推荐
linux之if语句详解
发布评论