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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…