5
shell脚本判断2个整数大小比较出现逻辑错误
source link: https://blog.51cto.com/u_14045290/5938453
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
shell脚本判断2个整数大小比较出现逻辑错误
精选 原创情况描述:当时写一个使用单分支if语句和read读入实现整数大小比较
当时写的脚本如下
#! /bin/bash
read -p "ple input second number:" a1 b1
expr 10 + $a1 &>/dev/null
RETVAL1=$?
expr 10 + $b1 &>/dev/null
RETVAL2=$?
if [ $RETVAL1 -ne 0 -o $RETVAL2 -ne 0 ]
then
echo "ple input two int number"
exit 1
fi
if [ "$a1" -gt "$b1" ] ; then
echo "$a1">"$b1"
exit 1
fi
if [ "$a1" -ge "$b1" ] ;then
echo "$a1"="$b1"
exit 1
fi
if [ "$a1" -lt "$b1" ] ;then
echo "$a1" < "$b1"
exit 1
fi
read -p "ple input second number:" a1 b1
expr 10 + $a1 &>/dev/null
RETVAL1=$?
expr 10 + $b1 &>/dev/null
RETVAL2=$?
if [ $RETVAL1 -ne 0 -o $RETVAL2 -ne 0 ]
then
echo "ple input two int number"
exit 1
fi
if [ "$a1" -gt "$b1" ] ; then
echo "$a1">"$b1"
exit 1
fi
if [ "$a1" -ge "$b1" ] ;then
echo "$a1"="$b1"
exit 1
fi
if [ "$a1" -lt "$b1" ] ;then
echo "$a1" < "$b1"
exit 1
fi
测试结果不符合逻辑
修改后如下代码
#! /bin/bash
read -p "ple input second number:" a1 b1
expr 10 + $a1 &>/dev/null
RETVAL1=$?
expr 10 + $b1 &>/dev/null
RETVAL2=$?
if [ $RETVAL1 -ne 0 -o $RETVAL2 -ne 0 ]
then
echo "ple input two int number"
exit 1
fi
if [ "$a1" -gt "$b1" ] ; then
echo "$a1>$b1"
exit 1
fi
if [ "$a1" -ge "$b1" ] ;then
echo "$a1=$b1"
exit 1
fi
if [ "$a1" -lt "$b1" ] ;then
echo "$a1 < $b1"
exit 1
fi
read -p "ple input second number:" a1 b1
expr 10 + $a1 &>/dev/null
RETVAL1=$?
expr 10 + $b1 &>/dev/null
RETVAL2=$?
if [ $RETVAL1 -ne 0 -o $RETVAL2 -ne 0 ]
then
echo "ple input two int number"
exit 1
fi
if [ "$a1" -gt "$b1" ] ; then
echo "$a1>$b1"
exit 1
fi
if [ "$a1" -ge "$b1" ] ;then
echo "$a1=$b1"
exit 1
fi
if [ "$a1" -lt "$b1" ] ;then
echo "$a1 < $b1"
exit 1
fi
测试结果如下
反思总结:一个小小的标点符号不正确就会导致整个代码逻辑都不正确;
echo “后面用双引号括起里面的字符”
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK