【问题标题】:How can I control inputs on Shell Script?如何控制 Shell 脚本的输入?
【发布时间】:2009-11-03 22:05:37
【问题描述】:

我正在从用户获取参数 ./inputControl.sh param1 param2 ... 我希望用户只能输入数字。不能输入任何文字等。

如果他们输入单词,我会告诉他们错误。

感谢回答

【问题讨论】:

  • 你需要接受浮点数还是整数?

标签: linux bash shell


【解决方案1】:

Bash 对正则表达式的支持还算不错

#!/usr/bin/bash
param1=$1
param2=$2

number_regex="^[0-9]+$"

if ![[ $param1 ]] || [[ $param1 !~ $number_regex ]] ; then
    echo Param 1 must be a number
    exit 1
fi
if ![[ $param2 ]] || [[ $param2 !~ $number_regex ]] ; then
    echo Param 2 must be a number
    exit 1
fi

如果您也可以接受浮点数,那么您可以将number_regex 设置为:

"^[+-]?[0-9]+\.?[0-9]*$"

"^[+-]?[0-9]+\.?[0-9]*([eE][+-]?[0-9]+)?$"

(最后两个正则表达式未经测试,可能不太正确)。

【讨论】:

  • "^[+-]?[0-9]+$" 允许负整数
  • 我找不到对 !~ 的任何引用,并且它在我的 Bash 3.2 中不起作用。您的 if 语句可以重写并简化为: if [[ ! param1 || ! $param1 =~ $number_regex ]].
【解决方案2】:

示例:检查数字

$ echo 1234d | awk '{print $0+0==$0?"yes number":"no"}'
no
$ echo 1234 | awk '{print $0+0==$0?"yes number":"no"}'
yes number

【讨论】:

    【解决方案3】:

    Bash 正则表达式很方便,但它们仅在 3.1 中引入,并在 3.2 中更改了引用规则。

    [[ 'abc' =~ '.' ]]  # fails in ≤3.0
                        # true in  =3.1
                        # false in ≥3.2
                        #   except ≥4.0 with "shopt -s compat31"
    [[ 'abc' =~ . ]]    # fails in ≤3.0
                        # true in  ≥3.1
    

    而且一开始它们甚至都不是必需的! expr 一直是一个标准的 shell 实用程序,永远支持正则表达式,并且适用于非 GNU 和非 Bash 系统。 (它使用basic (old) regular expressionsgrep,而不是extended (new) regular expressionsegrep。)

    expr 'abc' : '.'        # outputs '1' (characters matched), returns 0 (success)
    expr 'abc' : '.\(.\).'  # outputs 'b' (group matched), returns 0 (success)
    expr 'abc' : ....       # outputs '0', returns 1 (failure)
    

    【讨论】:

      【解决方案4】:

      我不知道你怎么能轻易做到这一点。我会使用提供正则表达式的 perl 或 python 脚本,这样会更容易。

      【讨论】:

        猜你喜欢
        • 2017-01-06
        • 1970-01-01
        • 2015-05-08
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        • 2020-05-13
        • 2016-04-05
        相关资源
        最近更新 更多