简体   繁体   English

在 bash shell 脚本中检查字符串是否仅包含数字的比较问题

[英]Problem with comparison for checking that a string contains only digits in a bash shell script

I am having to modify a bash shell script, but I don't have much experience with bash shell scripting (I have worked with many other languages, but just not much with shell scripting).我不得不修改一个 bash shell 脚本,但我对 bash shell 脚本没有太多经验(我使用过许多其他语言,但对 shell 脚本编写的不多)。

The script displays a menu with "X" items, and then it prompts the user to enter a number.该脚本显示一个带有“X”项的菜单,然后提示用户输入一个数字。

After the user enters a number, I think that the script checks the number/string that was entered to make sure it is a digit (I think) and then also if the number is within a range of values.用户输入数字后,我认为脚本会检查输入的数字/字符串以确保它是数字(我认为),然后检查数字是否在某个值范围内。

Part of what I want to change is the number of items in the menu and there were originally 9 items, but I need to add another 10 or so.我想要更改的部分内容是菜单中的项目数,最初有 9 个项目,但我需要再添加 10 个左右。 It looks like the check is failing if the number entered is more than 1 digit.如果输入的数字超过 1 位,则检查似乎失败。

Here's the snippet where it is doing the check:这是它进行检查的片段:

while menu && read -rp "$prompt" num && [[ "$num" ]]; do
    if [[ "$num" == [[:digit:]] ]] && [[ $num -gt 0 ]] && [[ $num -le ${#service_accounts[@]} ]]; then

I think the part of the "if" that is failing is:我认为失败的“如果”部分是:

[[ "$num" == [[:digit:]] ]] 

Can someone tell me if that comparison would fail if the string in $num is more than 1 digit?如果 $num 中的字符串超过 1 位,有人能告诉我比较会失败吗?

And, also, if that is the case, how can I change that comparison to work correctly even if the $num has more than 1 digit?而且,如果是这种情况,即使 $num 超过 1 位,我该如何更改该比较以使其正常工作?

Sorry if this is a kind of odd type of question :(!! And, thanks in advance!对不起,如果这是一种奇怪的问题:(!!而且,提前致谢!

Jim吉姆

[[ "$num" == [[:digit:]] ]] fails with everything but one digit. [[ "$num" == [[:digit:]] ]]失败,除了一位数之外的所有内容。


This enables your script to accept numbers with one to two digits:这使您的脚本能够接受一到两位数字:

[[ "$num" =~ ^[[:digit:]]{1,2}$ ]]

=~ compares $num with regex ^[[:digit:]]{1,2}$ . =~将 $num 与正则表达式^[[:digit:]]{1,2}$

See: The Stack Overflow Regular Expressions FAQ请参阅:堆栈溢出正则表达式常见问题解答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM