shell编程中的条件判断
shell编程中的条件判断
条件
if-then
case
if-then
单条件
if command
then
commands
fi
当command返回码为0时 条件成立
if.sh
#! /bin/bash
if date
then
echo "command exec"
fi
if date123
then
echo "command exec1"
fi
echo "out if"
[root@localhost110 sh]# ./if.sh
2016年 10月 29日 星期六 10:39:18 EDT
command exec
./if.sh: line 8: date123: command not found
out if全覆盖
if command
then
commands
else
commands
fi
if.sh
#! /bin/bash
if date1
then
echo "command"
echo "ok"
else
echo "commond1"
echo "fail"
fi
[root@localhost110 sh]# ./if.sh
./if.sh: line 2: date1: command not found
commond1
fail条件嵌套
if command1
then
commands
if command2
then
commands
fi
commands
fi
多条件
if command1
then
commands
elif command2
then
commands
else
commands
fi
test命令:
第一种形式
if test condition
then
commands
fi
第二种形式
中括号 []
if [ condition ]
then
commands
fi
复合条件判断
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
condition左右2边一定需要有空格 否者不能正确的执行
三类条件
数值比较
字符串比较
文件比较
if.sh
echo plese input a num
read num
if [ $num -gt 10 ]
then
echo "the num>10"
fi
if [ $num -lt 10 ] && [ $num -gt 5 ]
then
echo "the 5<num<10"
fi
[root@localhost110 sh]# ./if.sh
plese input a num
11
the num>10常用判断条件
数值比较
= n1 -eq n2
>= n1 -ge n2
> n1 -gt n2
< n1 -lt n2
<= n1 -le n2
!= n1 -ne n2
compare.sh及其调用结果
#! /bin/bash
if [ $1 -eq $2 ]
then
echo "$1=$2"
elif [ $1 -gt $2 ]
then
echo "$1>$2"
else
echo "$1<$2"
fi
运行结果
[root@localhost110 sh]# ./compare.sh 1 1
1=1
[root@localhost110 sh]# ./compare.sh 1 2
1<2
[root@localhost110 sh]# ./compare.sh 2 1
2>1
[root@localhost110 sh]# ./compare.sh 1 a
./compare.sh: line 3: [: a: integer expression expected
./compare.sh: line 6: [: a: integer expression expected
1<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)) then echo $1,$2; echo $1\<$2; elif (($1==$2)) then echo $1==$2 else echo $1\>$2 fi
case
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands3;;
*) default commands ;;
esac