方括号中的壳间距 [英] Shell spacing in square brackets
问题描述
作为初学者,我没有在任何地方找到答案,关于间距(语法)和解析的规则.
As a beginner, I did not find answered anywhere, the rules about spacing (grammar) and parsing.
例如.
我可以吗
if [$# -eq 2] ;
then
llll
fi
或者我必须在对象之间总是有一两个空白,如
or must I always have a blank or two between the objects, as
if [ $# -eq 2 ] ;
then
llll
fi
和第二个相关问题是关于
and the second related question is about the difference between
if [[ $# -eq 2 ]] ;
then
wafwaf
fi
我担心的是[
, ]
之前/之后的间距.
The concern I have is about spacing before/after [
, ]
.
没有搜索为我提供了一套规则.
No searching has provided me with a set of rules.
推荐答案
[
之后和 ]
之前需要空格.
Spaces are required after [
and before ]
.
[
实际上是一个命令的名称,test
的别名.这不是一个特殊的符号,它只是一个名字不寻常的命令.
[
is actually the name of a command, an alias fortest
. It's not a special symbol, it's just a command with an unusual name.
$ help '['
[: [ arg... ]
Evaluate conditional expression.
This is a synonym for the "test" builtin, but the last argument must
be a literal `]', to match the opening `['.
因为是普通命令名,不是特殊字符,所以[
后面需要一个空格.如果省略空格并写入 [foo
,shell 将在 $PATH
中搜索名为 [foo
的命令.
Because it's an ordinary command name and not a special character, a space is required after the [
. If you omit the space and write [foo
the shell will search the $PATH
for a command named [foo
.
$ [ foo = foo ] && echo true
true
$ [foo = foo] && echo true
[foo: command not found
为了可读性,[
期望它的最后一个参数正好是 ]
.作为一个普通的命令行参数,]
前必须有一个空格.如果没有空格,那么括号将成为前一个参数的最后一个字符,并且 [
会抱怨它的最后一个参数不是 ]
.
For readability's sake, [
expects its last argument to be exactly ]
. Being an ordinary command-line argument, ]
must have a space before it. If there's no space then the bracket will become the last character of the previous argument, and [
will complain about its last argument not being ]
.
$ [ foo = foo]
bash: [: missing `]'
$ [ foo = 'foo]'
bash: [: missing `]'
[[
是一个 bash 增强功能,比 [
有更多的特性,即对不带引号的变量名的处理更加合理.它需要两端有一个空格,与 [
相同.然而 [[
实际上是特殊的 shell 语法并且解析方式不同.它不是 [
那样的普通命令".
[[
is a bash enhancement with more features than [
, namely saner handling of unquoted variable names. It requires the a space on both ends, same as [
. However [[
is in fact special shell syntax and is parsed differently. It's not an "ordinary command" the way [
is.
[
和 [[
区别的详细说明见:
For a detailed explanation of the difference between [
and [[
, see:
这篇关于方括号中的壳间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!