考虑一下,下面的代码按预期工作:
if [[ $SOME_VARIABLE = "TRUE" ]]; then
echo "Only echoed when \$SOME_VARIABLE stores string \"TRUE\"."
fi
但是当我删除相等运算符周围的空间时,它总是评估为 0 退出状态(至少这是我认为它必须返回的值,因为它被视为 true):
if [[ $SOME_VARIABLE="TRUE" ]]; then
echo "Always true."
fi
UPDATE:
只是为了确认问题是否在于相等运算符:
#!usr/bin/ksh
SOME_VARIABLE=FALSE
if [[ $SOME_VARIABLE == "TRUE" ]]; then
echo "Only echoed when \$SOME_VARIABLE stores string \"TRUE\"."
fi
if [[ $SOME_VARIABLE=="TRUE" ]]; then
echo "Always true."
fi
[kent@TEST]$ sh test.sh
Always true.
UPDATE:
概括:
- Using
=
是相同的==
上面,但是已经过时了。
- 时刻注意你的空间。
From ksh(1)
:
条件表达式。
A conditional expression is used with the [[ compound command to test
attributes of files and to compare strings. Field splitting and file
name generation are not performed on the words between [[ and ]]. Each
expression can be constructed from one or more of the following unary
or binary expressions:
**string** True, if string is not null.
...
所以下面的表达式是正确的:
[[ somestring ]]
现在考虑你的第二个例子:
if [[ $SOME_VARIABLE="TRUE" ]]; then
假设$SOME_VARIABLE
是“SOMETHINGNOTTRUE”,这扩展到:
if [[ SOMETHINGNOTTRUE=TRUE ]]; then
“SOMETHINGNOTTRUE=TRUE”是一个非零长度字符串。因此这是真的。
如果你想在里面使用运算符[[
,您必须按照文档中的规定在它们周围放置空格(注意空格):
string == pattern
True, if string matches pattern. Any part of pattern can be
quoted to cause it to be matched as a string. With a successful
match to a pattern, the .sh.match array variable will contain
the match and sub-pattern matches.
string = pattern
Same as == above, but is obsolete.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)