Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何控制Shell脚本上的输入?_Linux_Bash_Shell - Fatal编程技术网

Linux 如何控制Shell脚本上的输入?

Linux 如何控制Shell脚本上的输入?,linux,bash,shell,Linux,Bash,Shell,我正在从用户获取参数。/inputControl.sh param1 param2。。。 我希望用户只能输入数字。不能输入任何单词等 如果他们输入word,我将向他们显示错误 谢谢你的回答我不知道你怎么能轻松做到这一点。我会使用提供regexp的perl或python脚本,这会更简单。Bash对正则表达式的支持还不错 #!/usr/bin/bash param1=$1 param2=$2 number_regex="^[0-9]+$" if ![[ $param1 ]] || [[ $par

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

如果他们输入word,我将向他们显示错误


谢谢你的回答

我不知道你怎么能轻松做到这一点。我会使用提供regexp的perl或python脚本,这会更简单。

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\u regex
设置为类似以下内容:

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


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

示例:检查数字

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

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
而且它们根本就不是必需的!一直以来,它都是一个标准的shell实用程序,支持regex,并且在非GNU和非Bash系统上工作。(它使用like
grep
,而不是like
egrep


您需要接受浮点还是只接受整数?和
“^[+-]?[0-9]+$”
才能允许负整数我找不到任何
的引用~并且它在我的Bash3.2中不起作用。您的
if
语句可以重写并简化为:if
[!param1 | |!$param1=~$number_regex]
[[ '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 'abc' : '.'        # outputs '1' (characters matched), returns 0 (success)
expr 'abc' : '.\(.\).'  # outputs 'b' (group matched), returns 0 (success)
expr 'abc' : ....       # outputs '0', returns 1 (failure)