5

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

 1 year ago
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.
neoserver,ios ssh client

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

精选 原创

shenshushu 2022-12-14 23:04:56 博主文章分类:shell ©著作权

文章标签 双引号 if语句 shell 文章分类 Linux 系统/运维 阅读数213

情况描述:当时写一个使用单分支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个整数大小比较出现逻辑错误_if语句_02

修改后如下代码

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

测试结果如下

shell脚本判断2个整数大小比较出现逻辑错误_双引号_04

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

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

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK