如何在 bash 脚本中进行字符比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39550623/
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
How to do character comparison in bash scripts?
提问by posixKing
Here is my code
这是我的代码
#! /bin/bash
read var
if [ $var="Y" -o $var="y" ]
then
echo "YES"
else
echo "NO"
fi
I want to print YES if the user presses y or Y, otherwise I want to print NO. Why doesn't this code work?
如果用户按 y 或 Y,我想打印 YES,否则我想打印 NO。为什么这段代码不起作用?
回答by makadev
Basically, your Condition is wrong. Quote your variables and leave spaces between operators (like shellter wrote). So it should look like:
基本上,您的条件是错误的。引用您的变量并在运算符之间留出空格(如 shellter 所写)。所以它应该看起来像:
#! /bin/bash
read var
if [ "$var" = "Y" ] || [ "$var" = "y" ]
then
echo "YES"
else
echo "NO"
fi
Edit: for POSIX ccompatibility
编辑:为了 POSIX 兼容性
- Replaced
==
with=
- see comments - Replaced
-o
syntax with||
syntax - see comments
- 替换
==
为=
- 见评论 -o
用||
语法替换语法- 见评论
回答by SLePort
With Bash, you can also use regular expression in your test with the =~
operator:
使用 Bash,您还可以在测试中使用正则表达式与=~
运算符:
read var
[[ "$var" =~ [Yy] ]] && echo "YES" || echo "NO"
Or as Benjamin W. mentionned, simply use character range with the ==
operator:
或者正如 Benjamin W. 所提到的,只需将字符范围与==
运算符一起使用:
read var
[[ "$var" == [Yy] ]] && echo "YES" || echo "NO"
回答by Jorvis
There is minor syntax error in your code.
您的代码中存在轻微的语法错误。
Correction : There should be a white space between operators and variables
更正:运算符和变量之间应该有一个空格
read var
if [ $var = "Y" -o $var = "y" ]
then
echo "YES"
else
echo "NO"
fi
Try the above bash script.
试试上面的 bash 脚本。
Hope it would work fine.
希望它能正常工作。
Happy Coding!
快乐编码!
回答by Gary Dean
If all you require is a upper/lowercase comparison, use the ,,
operator on the variable being compared ( note the ${var,,}
):
如果您只需要大写/小写比较,,,
请在要比较的变量上使用运算符(注意${var,,}
):
#!/bin/bash
read var
if [ ${var,,} = "y" ]
then
echo "YES"
else
echo "NO"
fi
or more succinctly:
或更简洁地说:
#!/bin/bash
read var
[ ${var,,} = 'y' ] && echo 'YES' || echo 'NO'
or the way I might actually do it:
或者我可能实际做的方式:
#!/bin/bash
read var
[[ "${var,,}" == 'y' ]] && echo 'YES' || echo 'NO'
回答by ABN
Below is the code that I tried.
下面是我试过的代码。
#! /bin/bash
read -p "Are you Sure?(Y/N) " answer
if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then
echo "Do your stuff."
else
echo "Do your other stuff"
fi
Add whitespace around '=' and your code will run fine.
在 '=' 周围添加空格,您的代码将运行良好。
#! /bin/bash
read var
if [ $var = "Y" -o $var = "y" ]
then
echo "YES"
else
echo "NO"
fi