使用正则表达式验证 Bash 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9517888/
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
Bash parameter verification using regex
提问by Ramon Saraiva
I don't how to use regex properly in bash, i got an error trying to do in this way, what is wrong in that regex verification?
我不知道如何在 bash 中正确使用正则表达式,尝试以这种方式执行时出错,正则表达式验证有什么问题?
#!/bin/bash
if [ ! $# -eq 1 ]; then
echo "Error: wrong parameters"
else
if [ =~ "[a-z]" ]; then
echo ": word"
elif [ =~ "[0-9]" ]; then
echo ": number"
else
echo ": invalid parameter"
fi
fi
回答by darryn.ten
I have reworked your script and get the expected result with the following:
我已经重新编写了您的脚本并使用以下内容获得了预期结果:
#!/bin/bash
if [ ! $# -eq 1 ]; then
echo "Error: wrong parameters"
else
if [[ =~ ^[a-z]+$ ]]; then
echo ": word"
elif [[ =~ ^[0-9]+$ ]]; then
echo ": number"
else
echo ": invalid parameter"
fi
fi
You do not need to quote your Regex.
您不需要引用您的正则表达式。
回答by l0b0
Don't quote the regex, and use double brackets:
不要引用正则表达式,并使用双括号:
[[ "" =~ [a-z] ]]
It's not strictly necessary to quote the variable in this specific case, but it doesn't hurt and it's good practice to always quote strings which contain variables because of the very, very numerous pitfalls related to word splitting.
在这种特定情况下引用变量并不是绝对必要的,但它并没有什么坏处,而且总是引用包含变量的字符串是一种很好的做法,因为与分词相关的陷阱非常非常多。
回答by asf107
Use two brackets :
使用两个括号:
if [[ "" =~ [a-z] ]] ; then

