shell脚本判断2个整数大小比较出现逻辑错误

时间:2022-12-15 11:20:27

情况描述:当时写一个使用单分支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

shell脚本判断2个整数大小比较出现逻辑错误

测试结果不符合逻辑

shell脚本判断2个整数大小比较出现逻辑错误

修改后如下代码

#! /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

shell脚本判断2个整数大小比较出现逻辑错误

测试结果如下

shell脚本判断2个整数大小比较出现逻辑错误


反思总结:一个小小的标点符号不正确就会导致整个代码逻辑都不正确;

echo “后面用双引号括起里面的字符”