shell编程中的条件判断
条件
if-then
caseif-then
单条件
if command
then
commands
fi
当command返回码为0时 条件成立if.sh#! /bin/bashif datethenecho "command exec"fiif date123thenecho "command exec1"fiecho "out if"[root@localhost110 sh]# ./if.sh2016年 10月 29日 星期六 10:39:18 EDTcommand exec./if.sh: line 8: date123: command not foundout if全覆盖if command
then
commands
else
commands
fiif.sh#! /bin/bashif date1thenecho "command"echo "ok"elseecho "commond1"echo "fail"fi[root@localhost110 sh]# ./if.sh./if.sh: line 2: date1: command not foundcommond1fail条件嵌套if command1
then
commands
if command2
then
commands
fi
commands
fi多条件
if command1
then
commands
elif command2
then
commands
else
commands
fitest命令:
第一种形式
if test condition
then
commands
fi
第二种形式
中括号 []
if [ condition ]
then
commands
fi复合条件判断
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]condition左右2边一定需要有空格 否者不能正确的执行三类条件
数值比较
字符串比较
文件比较
if.shecho plese input a numread numif [ $num -gt 10 ]thenecho "the num>10"fiif [ $num -lt 10 ]&& [ $num -gt 5 ]thenecho "the 5<num<10"fi
[root@localhost110 sh]# ./if.shplese input a num11the num>10常用判断条件
数值比较
= n1 -eq n2
>= n1 -ge n2
> n1 -gt n2
< n1 -lt n2
<= n1 -le n2
!= n1 -ne n2
compare.sh及其调用结果#! /bin/bashif [ $1 -eq $2 ]thenecho "$1=$2"elif [ $1 -gt $2 ]thenecho "$1>$2"elseecho "$1<$2"fi运行结果[root@localhost110 sh]# ./compare.sh1 11=1[root@localhost110 sh]# ./compare.sh1 21<2[root@localhost110 sh]# ./compare.sh2 12>1[root@localhost110 sh]# ./compare.sh 1 a./compare.sh: line 3: [: a: integer expression expected./compare.sh: line 6: [: a: integer expression expected1<a字符串比较
str1 = str2 相同
str1 != str2 不同
str1 > str2 str1比str2大 (ascll码逐位比较)
str1 < str2 str1比str2小
-n str1 字符串长度是否非0
-z str1 字符串长度是否为0文件比较
-d file 检查file是否存在并是一个目录
-e file 检查file是否存在
-f file 检查file是否存在并是一个文件
-s file 检查file是否存在并非空file1 -nt file2 检查file1是否比file2新
file1 -ot file2 检查file1是否比file2旧-r file 检查file是否存在并可读
-w file 是否存在并可写
-x file 是否存在并可执行
-O file 是否存在并属当前用户所有
-G file 是否存在并且默认组与当前用户相同高级判断
(( expression )) 高级数学表达式
[[ expression ]] 高级字符串比较if (($1<$2))thenecho $1,$2;echo $1<$2;elif (($1==$2))then echo $1==$2elseecho $1>$2fi casecase variable in
pattern1 | pattern2) commands1;;
pattern3) commands3;;
*) default commands ;;
esac#! /bin/bashcase $1 in 1|11|111)echo 1_$1;; 2)echo 2_$1;echo 2_$1;;3)echo 3_$1;;esac本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/137230.htm