korn shell 错误 [: 缺少 `]'
korn shell error [: missing `]'
我正在学习基于 Bourne shell 的 Korn shell。下面是我非常简单的代码。
read ab
if [ $ab = "a" || $ab = "A" ] ; then
echo hi
fi
出于某种原因 ||
运算符给我错误:
[: missing `]'
a: command not found
if
条件的正确写法是:
read ab
if [ "$ab" = "a" ] || [ "$ab" = "A" ]; then
echo hi
fi
对于[ ... ]
,必须将变量放在双引号中。否则,如果变量展开为空或者它们的展开包含空格,shell 将失败并出现语法错误。
另请参阅:
- Why should there be a space after '[' and before ']' in Bash?
- How to use double or single brackets, parentheses, curly braces
- BashFAQ - What is the difference between test, single, and double brackets?
如果您使用 ksh 或现代 bash,您可以使用非标准 [[
... ]]
而不是 [
... ]
.
这有两个好处:
- 您可以在
[[
中使用 ||
... ]]
- 变量扩展不需要引号。
这样写起来更安全也更短
[[ $ab = a || $ab = A ]]
我正在学习基于 Bourne shell 的 Korn shell。下面是我非常简单的代码。
read ab
if [ $ab = "a" || $ab = "A" ] ; then
echo hi
fi
出于某种原因 ||
运算符给我错误:
[: missing `]'
a: command not found
if
条件的正确写法是:
read ab
if [ "$ab" = "a" ] || [ "$ab" = "A" ]; then
echo hi
fi
对于[ ... ]
,必须将变量放在双引号中。否则,如果变量展开为空或者它们的展开包含空格,shell 将失败并出现语法错误。
另请参阅:
- Why should there be a space after '[' and before ']' in Bash?
- How to use double or single brackets, parentheses, curly braces
- BashFAQ - What is the difference between test, single, and double brackets?
如果您使用 ksh 或现代 bash,您可以使用非标准 [[
... ]]
而不是 [
... ]
.
这有两个好处:
- 您可以在
[[
中使用||
...]]
- 变量扩展不需要引号。
这样写起来更安全也更短
[[ $ab = a || $ab = A ]]