shell比较两个整数大小并严格判断参数输入脚本

该博客分享了一个使用Shell脚本进行整数比较的技巧,并介绍了如何确保脚本接收到的参数是有效的数字,从而进行严格的参数输入验证。

代码如下


#!/bin/sh
[ $# -ne 2 ] && {
   echo "USAGE: $0 agr1 arg2 "
   exit 1
}

expr $1 + 0 &>/dev/null
if [ $? -ne 0 ] ;then
   echo "$1 is not int"
   exit 1
fi

expr $2 + 0 &>/dev/null
if [ $? -ne 0 ] ;then
   echo "$2 is not int"
   exit
fi

if [ $1 -gt $2 ]
then 
   echo "$1 > $2"
elif [ $1 -eq $2 ]
 then 
   echo "$1 = $2"
else
   echo "$1 < $2"
fi
~      

访问方式:

[root1@bogon shelldir]$ sh campareInt.sh 1 9
1 < 9
[root1@bogon shelldir]$ sh campareInt.sh 4 3
4 > 3
[root1@bogon shelldir]$ sh campareInt.sh a 1
a is not int

判断一个字符串是否为数字的方法

expr $1 "+" 10 &> /dev/null
if [ $? -eq 0 ];then
  echo "$1 is number"
else
  echo "$1 not number"
fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值