shell 双多分支if条件句语法

比较两个数大小的语法:
[root@dbserver ~]# cat if_01_01
read -p "please input two number:" a b
if [ $a -gt $b ]
then
echo "yes,$a > $b"
elif [ $a -eq $b ]
then
echo "yes,$a = $b"
else
echo "yes,$a < $b"
fi
执行结果:
[root@dbserver ~]# sh if_01_01
please input two number:4 5
yes,4 < 5
[root@dbserver ~]# sh if_01_01
please input two number:4 4
yes,4 = 4
[root@dbserver ~]# sh if_01_01
please input two number:5 4
yes,5 > 4

传参程序,目的在于判断输入值的合法性,首先是参数的个数是否满足两个.
[root@dbserver ~]# vi if_01_01.sh
#!/bin/bash
a=$1
b=$2
if [ $# -ne 2 ] ----说明:$# 获取当前shell命令行中参数的总个数

then
echo "Usage:sh $0 num1 num2"
exit
fi
if
[ $a -gt $b ]
then
echo "yes,$a > $b"
elif
[ $a -lt $b ]
then
echo "yes,$a < $b"
else
echo "yes,$a = $b"
执行结果:
[root@dbserver ~]# sh if_01_01.sh 2 3 4
Usage:sh if_01_01.sh num1 num2

现在同时判断输入参数是否为两个以及参数的正确性.
[root@dbserver ~]# cat if_01_01.sh
#!/bin/bash
a=$1
b=$2
if [ $# -ne 2 ]
then
echo "Usage:sh $0 num1 num2"
exit
fi
[ -n "echo $1|sed ‘s/[0-9]//g‘" ] && echo "the first data must be number" && exit 1 -----说明:sed s/要替换的字符串/新的字符串/g
[ -n "echo $2|sed ‘s/[0-9]//g‘" ] && echo "the second data must be number" && exit 1
if
[ $a -gt $b ]
then
echo "yes,$a > $b"
elif
[ $a -eq $b ]
then
echo "yes,$a = $b"
else
echo "yes,$a < $b"
fi
执行结果:
[root@dbserver ~]# sh if_01_01.sh 2 3k
the second data must be number
[root@dbserver ~]# sh if_01_01.sh 2k 3
the first data must be number
[root@dbserver ~]# sh if_01_01.sh 2k 3k
the first data must be number
[root@dbserver ~]# sh if_01_01.sh 2 36
yes,2 < 36

shell 双多分支if条件句语法

上一篇:Shell脚本编程基础之shell脚本命令执行顺序


下一篇:windows做时间服务器,linux和windows时间同步