实战1: 输入2个整数,判断大小
三种方式实现:
1定义变量 2 脚本传参 3 read读入
第一步,给用户提示,让其输入整数
第二步,判断第一个值和第二个值不为空
第三步,判断两个数为整数
第四步,第一个值与第二个值对比[root@mysql-5 scripts]# cat test21.sh
#!/bin/bash
cat <
1-10... zhengshu
EOF
read -p "panduan daxiao:" a b
[ ${#a} -eq 0 ]&&{
echo "diyigecanshu"
exit 1
}
[ ${#b} -eq 0 ]&&{
echo "diergecanshu"
exit 1
}
expr $a + 1 &>/dev/null
RE_A=$?
expr $b + 1 &>/dev/null
RE_B=$?
if [ $RE_A -ne 0 -o $RE_B -ne 0 ]
then
echo "one of you input is not int"
exit 1
fi
if [ $a -eq $b ];
then
echo "$a = $b"
elif [ $a -gt $b ]
then
echo "$a > $b"
else
echo "$a
fi
[root@mysql-5 scripts]# sh test2
test20.sh test21.sh test2.sh
[root@mysql-5 scripts]# sh test21.sh
1-10... zhengshu
panduan daxiao:e e
one of you input is not int
[root@mysql-5 scripts]# sh test21.sh
1-10... zhengshu
panduan daxiao:2 34
2
[root@mysql-5 scripts]# sh test21.sh
1-10... zhengshu
panduan daxiao:3 3
3 = 3
[root@mysql-5 scripts]#
脚本传参方式实现
我这里是对上面进行了改变。进到vim里面
%s#$a#$1#g %s#$b#$2#g在删除几行,就实现了脚本传参的方式
[root@mysql-5 scripts]# cat test22.sh
#!/bin/bash
[ ${#1} -eq 0 ]&&{
echo "diyigecanshu"
exit 1
}
[ ${#2} -eq 0 ]&&{
echo "diergecanshu"
exit 1
}
expr $1 + 1 &>/dev/null
RE_A=$?
expr $2 + 1 &>/dev/null
RE_B=$?
if [ $RE_A -ne 0 -o $RE_B -ne 0 ]
then
echo "one of you input is not int"
exit 1
fi
if [ $1 -eq $2 ];
then
echo "$1 = $2"
elif [ $1 -gt $2 ]
then
echo "$1 > $2"
else
echo "$1
fi
[root@mysql-5 scripts]# sh test22.sh 3 d
one of you input is not int
[root@mysql-5 scripts]# sh test22.sh 3 4
3
[root@mysql-5 scripts]# sh test22.sh 3 3
3 = 3
[root@mysql-5 scripts]#
定义变量的方式
这里我用以下命令替换了以下原有的变量,进行测试
[root@mysql-5 scripts]# sh test23.sh
3
[root@mysql-5 scripts]# sed -i "s#3#4#g" test23.sh
[root@mysql-5 scripts]# sh test23.sh
4 = 4
[root@mysql-5 scripts]# sed -i "s#4#dd#g" test23.sh
[root@mysql-5 scripts]# sh test23.sh
one of you input is not int
[root@mysql-5 scripts]# cat test23.sh
#!/bin/bash
a=dd
b=dd
[ ${#a} -eq 0 ]&&{
echo "diyigecanshu"
exit 1
}
[ ${#b} -eq 0 ]&&{
echo "diergecanshu"
exit 1
}
expr $a + 1 &>/dev/null
RE_A=$?
expr $b + 1 &>/dev/null
RE_B=$?
if [ $RE_A -ne 0 -o $RE_B -ne 0 ]
then
echo "one of you input is not int"
exit 1
fi
if [ $a -eq $b ];
then
echo "$a = $b"
elif [ $a -gt $b ]
then
echo "$a > $b"
else
echo "$a
fi
[root@mysql-5 scripts]#