我如何比较一个变量的字符串(并做一些事情,如果他们匹配)?
当前回答
Bash 4+示例。注意:当单词中包含空格时,不使用引号会导致问题。在我看来,总是用Bash引用。
下面是Bash 4+中的一些例子:
例1,在字符串中检查'yes'(不区分大小写):
if [[ "${str,,}" == *"yes"* ]] ;then
例2,检查字符串中的'yes'(不区分大小写):
if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
例3,检查字符串中的'yes'(区分大小写):
if [[ "${str}" == *"yes"* ]] ;then
例4,检查字符串中的'yes'(区分大小写):
if [[ "${str}" =~ "yes" ]] ;then
例5,精确匹配(区分大小写):
if [[ "${str}" == "yes" ]] ;then
例6,精确匹配(不区分大小写):
if [[ "${str,,}" == "yes" ]] ;then
例7,精确匹配:
if [ "$a" = "$b" ] ;then
享受。
其他回答
在if语句中使用变量
if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
如果你想在它们不匹配的时候做一些事情,用!=替换=。您可以在它们各自的文档中阅读更多关于字符串操作和算术操作的信息。
为什么在$x周围使用引号?
你需要在$x周围加上引号,因为如果$x为空,你的Bash脚本会遇到如下所示的语法错误:
if [ = "valid" ]; then
==运算符的非标准使用
请注意,Bash允许使用==与[相等,但这不是标准的。
使用第一种情况,其中$x周围的引号是可选的:
if [[ "$x" == "valid" ]]; then
或者使用第二种情况:
if [ "$x" = "valid" ]; then
我也曾在同样的情况下挣扎过一段时间,下面是我解决的方法:
if [ "$var1" == "$var2" ]; then
#dowhateveryouwant
fi
注意比较符号前后的空格,否则将不起作用,或者会得到意想不到的结果。
我花了很多时间在使用一个等号(=)上,但没有用。希望能有所帮助。
或者,如果你不需要else子句:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
我这样做,是兼容Bash和Dash (sh):
testOutput="my test"
pattern="my"
case $testOutput in (*"$pattern"*)
echo "if there is a match"
exit 1
;;
(*)
! echo there is no coincidence!
;;esac
Bash 4+示例。注意:当单词中包含空格时,不使用引号会导致问题。在我看来,总是用Bash引用。
下面是Bash 4+中的一些例子:
例1,在字符串中检查'yes'(不区分大小写):
if [[ "${str,,}" == *"yes"* ]] ;then
例2,检查字符串中的'yes'(不区分大小写):
if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
例3,检查字符串中的'yes'(区分大小写):
if [[ "${str}" == *"yes"* ]] ;then
例4,检查字符串中的'yes'(区分大小写):
if [[ "${str}" =~ "yes" ]] ;then
例5,精确匹配(区分大小写):
if [[ "${str}" == "yes" ]] ;then
例6,精确匹配(不区分大小写):
if [[ "${str,,}" == "yes" ]] ;then
例7,精确匹配:
if [ "$a" = "$b" ] ;then
享受。