bash 仅文件通配和匹配数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6683779/
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
File globbing and matching numbers only
提问by haunted85
In a bash script I need to verify that the user inputs actual numbers so I have thought the easiest way to make myself sure about that is implementing a case:
在 bash 脚本中,我需要验证用户是否输入了实际数字,因此我认为最简单的方法是实现case:
case in
[0-9]*)
echo "It's ok"
;;
*)
echo "Ain't good!"
exit 1
;;
esac
But I'm having hard time with file globbing because I can't find a way to demand the $1 value has to be numeric only. Or another way could be excluding all the alternatives:
但是我很难处理文件通配符,因为我找不到要求 $1 值只能是数字的方法。或者另一种方法可以排除所有替代方案:
case in
-*)
echo "Can't be negative"
exit 1
;;
+*)
echo "Must be unsigned"
exit 1
;;
*[a-zA-z]*)
echo "Can't contain letters"
exit 1
;;
esac
The thing is in this case I should be able to block "special" chars like ! ? ^ = ( ) and so forth... I don't know how to acheive it. Please anyone give me a hint?
事情是在这种情况下,我应该能够阻止“特殊”字符,例如 ! ? ^ = ( ) 等等......我不知道如何实现它。请任何人给我一个提示?
采纳答案by glenn Hymanman
If you find a non-numeric character anywhere in the string, the input is bad, otherwise it's good:
如果您在字符串中的任何位置找到非数字字符,则输入是错误的,否则是好的:
case "" in
*[^0-9]*) echo "first parameter must contain numbers only"; exit 1;;
esac
回答by wodny
Actually it would be better to use
实际上最好使用
*[!0-9]*
instead of
代替
*[^0-9]*
as the first one is POSIX and the second one is a bashism[1].
因为第一个是 POSIX,第二个是 bashism [1]。
[1] http://rgeissert.blogspot.com/2013/02/a-bashism-week-negative-matches.html
[1] http://rgeissert.blogspot.com/2013/02/a-bashism-week-negative-matches.html

