bash 如何检查传递给 shell 脚本的参数是否不是整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15745334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:03:14  来源:igfitidea点击:

How can I check whether an argument passed to a shell script is NOT an integer?

bashshellunixscriptingarguments

提问by Explosion Pills

I know how to check whether an argument is an integer using:

我知道如何使用以下方法检查参数是否为整数:

if [[  = *[[:digit:]]* ]]; then
    #  is a number
else
    #  is not a number
fi

However, I need to check whether the argument is nota integer. How can I do that?

但是,我需要检查参数是否不是整数。我怎样才能做到这一点?

回答by Explosion Pills

$2 = *[[:digit:]]*only checks whether $2containsa digit.

$2 = *[[:digit:]]*只检查是否$2包含数字。

# is an integer
[[  =~ ^[[:digit:]]+$ ]]
# is not an integer
[[ !  =~ ^[[:digit:]]+$ ]]

回答by jub0bs

A POSIX-compliant approach

符合 POSIX 的方法

A robust and portable (POSIX-compliant; tested in dash) approach is to check whether the shell can parse the variable as an integer, as demonstrated in the script below.

一种健壮且可移植(符合 POSIX 标准;在 中测试dash)的方法是检查 shell 是否可以将变量解析为整数,如下面的脚本所示。

#!/bin/sh

# test-int.sh
# A script that tests whether its first argument is an integer

if [ "" -eq 0 -o "" -ne 0 ] >/dev/null 2>&1; then
    printf "integer: %s\n" ""
else
    printf "not an integer\n"
fi

Tests

测试

$ dash test-int.sh foo
not an integer
$ dash test-int.sh 098234
integer: 098234
$ dash test-int.sh 77239asdfasf
not an integer
$ dash test-int.sh -77239
integer: -77239

Note that this approach also accepts negative integers out of the box, but you can easily modify it to only accept positive integers, for instance.

请注意,此方法还接受开箱即用的负整数,但您可以轻松地将其修改为仅接受正整数。

In my script, a successfully parsed integer is printed as a string, but, alternatively, you may want to print it as an integer, with %d.

在我的脚本中,成功解析的整数打印为string,但是,或者,您可能希望将其打印为integer,使用%d.

回答by The Dark Knight

Quite easy you know . You can do this :

很容易你知道。你可以这样做 :

   if echo $Myvar | egrep -q '^[0-9]+$'; then
      # $Myvar is a number
   else
      # $Myvar is not a number
   fi

This is some thing that i predominantly use for a number check.

这是我主要用于数字检查的一些东西。

回答by Till Varoquaux

You test only checks whether the input is a digit; for example is $2 is "43" then this will print: 43 is not a number Fixing your solution to check for actual numbers can be done with a regular expression:

您测试只检查输入是否为数字;例如 $2 是 "43" 那么这将打印: 43 is not a number 修复您的解决方案以检查实际数字可以使用正则表达式完成:

if [[  =~ ^-?[[:digit:]]+$ ]]; then
    echo " is a number"
fi

Checking whether the input is not a number is then just a matter of negating the test:

检查输入是否不是数字只是否定测试的问题:

if [[ !  =~ ^-?[[:digit:]]+$ ]]; then
    echo " is not a number"
fi