Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

string - 如何在Bash中比较字符串(How to compare strings in Bash)

如何将变量与字符串进行比较(如果匹配则执行某些操作)?

  ask by Erik Sapir translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using variables in if statements (在if语句中使用变量)

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

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. (您可以在各自的文档中阅读有关字符串运算算术运算的更多信息。)

Why do we use quotes around $x ? (为什么我们在$x周围使用引号?)

You want the quotes around $x , because if it is empty, your bash script encounters a syntax error as seen below: (您需要在$x周围加上引号,因为如果它为空,则bash脚本会遇到语法错误,如下所示:)

if [ = "valid" ]; then

Non-standard use of == operator (==运算符的非标准用法)

Note that bash allows == to be used for equality with [ , but this is not standard . (请注意, bash允许==用于与[相等[ ,但这不是标准的 。)

Use either the first case wherein the quotes around $x are optional: (使用第一种情况,其中$x左右的引号是可选的:)

if [[ "$x" == "valid" ]]; then

or use the second case: (或使用第二种情况:)

if [ "$x" = "valid" ]; then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...