如何在Bash中比较字符串 [英] How to compare strings in Bash
问题描述
如何将变量与字符串进行比较(如果匹配则执行某些操作)?
How do I compare a variable to a string (and do something if they match)?
推荐答案
在if语句中使用变量
if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
如果您想在它们不匹配时执行某些操作,请将=
替换为!=
.您可以阅读有关字符串操作和<在各自文档中的href ="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.3" rel ="noreferrer">算术运算.
If you want to do something when they don't match, replace =
with !=
. You can read more about string operations and arithmetic operations in their respective documentation.
您希望在$x
周围加上引号,因为如果它为空,则您的Bash脚本会遇到语法错误,如下所示:
You want the quotes around $x
, because if it is empty, your Bash script encounters a syntax error as seen below:
if [ = "valid" ]; then
==
运算符的非标准用法
请注意,Bash允许==
用于与[
相等,但是这不是标准.
Non-standard use of ==
operator
Note that Bash allows ==
to be used for equality with [
, but this is not standard.
使用第一种情况,其中$x
周围的引号是可选的:
Use either the first case wherein the quotes around $x
are optional:
if [[ "$x" == "valid" ]]; then
或使用第二种情况:
if [ "$x" = "valid" ]; then
这篇关于如何在Bash中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!