【站长推荐】#!/bin/bash# 需求:输入任意一个字符、判断是否为整数;然后再计算第一个字符与第二个字符之间的数。#01)输入任意字符echo -ne "请输入一个任意值:\t\t"read Num1echo -ne "请再次输入另一个任意数值:\t"read Num2#02)"X"防止未知错误出现if [ "X${Num1}" = "X" ] || [ "X${Num2}" = "X" ]then echo "输入的字符1或字符2,有一个为空" exit 1fi#03)用+1方式,判断输入是不是一个整数expr ${Num1} "+" 1 &> /dev/nullif [ $? -ne 0 ]then echo -e "输入的数值1:[${Num1}],不是一个整数" exit 2fiexpr ${Num2} "+" 1 &> /dev/nullif [ $? -ne 0 ]then echo "输入的数值2:[${Num2}],不是一个整数" exit 3fi#04)判断$Num1是否小于$Num2if [ ${Num1} -le ${Num2} ]then :else echo "输入的数值1:[${Num1}]大于输入的数值2:[${Num2}]" exit 4fi#05)输出$1与$2之间的整数for((i=$[ Num1 + 1 ];i<${Num2};i++))do echo "数值1与值2之间的整数为:[${i}]"done来自群组: 北京运维圈运维网 感谢您的阅读
– 本文出自运维网,原文地址:http://www.cnyunwei.com/thread-21370-1-1.html
https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash
One approach is to use a regular expression, like so:
re='^[0-9]+$'if ! [[ $yournumber =~ $re ]] ; then
echo "error: Not a number" >&2; exit 1fi
If the value is not necessarily an integer, consider amending the regex appropriately; for instance:
^[0-9]+([.][0-9]+)?$
…or, to handle negative numbers:
^-?[0-9]+([.][0-9]+)?$