shell脚本常用脚本:if判断
shell脚本常用脚本:if判断str1 = str2当两个串有相同内容、长度时为真
str1 != str2当串str1和str2不等时为真
-n str1当串的长度大于0时为真(串非空)
-z str1当串的长度为0时为真(空串)
str1当串str1为非空时为真
[ "2006.01.23" \> "2005.03.01" ] && echo dayu || echo budayu
int1 -eq int2两数相等为真
int1 -ne int2两数不等为真
int1 -gt int2int1大于int2为真
int1 -ge int2int1大于等于int2为真
int1 -lt int2int1小于int2为真
int1 -le int2int1小于等于int2为真
-r file用户可读为真
-w file用户可写为真
-x file用户可执行为真
-f file文件为正规文件为真
-d file文件为目录为真
-c file文件为字符特殊文件为真
-b file文件为块特殊文件为真
-s file文件大小非0时为真
-t file当文件描述符(默认为1)指定的设备为终端时为真
-a 与
-o或
!非
上面的三种写在括号内,对应的 && || 写在中括号之间。例如,if[ "$a"eq 1-o"$b" eq 2 ]&&[ "$c"eq3 ]
单分支结构
If [条件]
then
指令
fi
或
If [条件]; then
指令
fi
提示:分号相当于命令换行,上面两种语法相同,在脚本中一般使用第一种
脚本实例:
比较大小
# cat if01.sh
#!/bin/bash
#a=12
#b=11
read -p "pls input two number:" a b
if [ $a -gt $b ]
then
echo "yes $a > $b"
fi
if [ $a -lt $b ]
then
echo "yes $a < $b"
fi
if [ $a -eq $b ]
then
echo "yes $a = $b"
fi
方法二:
语法:
If [条件]
then
指令
else
指令
fi
双分支脚本实例:
比较大小
# cat if02.sh
#!/bin/bash
#a=12
#b=11
read -p "pls input two number:" a b
if [ $a -gt $b ]
then
echo "yes $a > $b"
else
if [ $a -lt $b ]
then
echo "yes $a < $b"
else
echo "yes $a = $b"
fi
fi
#传参做判断
# ./if04.sh
pls input two number:10
Usage :sh ./if04.sh num1 num2
# ./if04.sh
pls input two number:11 1 1
Usage :sh ./if04.sh num1 num2
# cat if04.sh
#!/bin/bash
#a=12
#b=11
read -p "pls input two number:" a b
if [ $# -ne 2 ]
then
echo "Usage :sh $0 num1 num2"
exit 1
elif [ $a -gt $b ]
then
echo "yes $a > $b"
elif [ $a -lt $b ]
then
echo "yes $a < $b"
else
echo "yes $a = $b"
fi
多分支结构
语法:
If [条件]
then
指令
elif [条件]
then
指令
elif [条件]
then
指令
elif [条件]
then
指令
… …
else
指令
fi
多分支脚本实例:
比较大小
# cat if03.sh
#!/bin/bash
#a=12
#b=11
read -p "pls input two number:" a b
if [ $a -gt $b ]
then
echo "yes $a > $b"
elif [ $a -lt $b ]
then
echo "yes $a < $b"
else
echo "yes $a = $b"
fi
传参判断方式计算:
# ./if05.sh 15 1f
第二个参数必须为数字
# ./if05.sh 1w 1
第一个参数必须为数字
# cat if05.sh
#!/bin/bash
a=$1
b=$2
#read -p "pls input two number:" a b
if [ $# -ne 2 ]
then
echo "Usage :sh $0 num1 num2"
exit 1
fi
[ -n "`echo $1 |sed 's///g'`" ] && echo "第一个参数必须为数字" && exit 1
[ -n "`echo $2 |sed 's///g'`" ] && echo "第二个参数必须为数字" && exit 1
if [ $a -gt $b ]
then
echo "yes $a > $b"
elif [ $a -lt $b ]
then
echo "yes $a < $b"
else
echo "yes $a = $b"
fi
页:
[1]