Ubuntu – builtin [ , -bash: [: missing `]’

bashcommand line

while going through learn bash the hard way, I found that [ and test are both commands and synonyms, and both are builtin.
As it is a builtin it should not give any error for builtin [ , but I am getting -bash: [: missing `]',
Can someone explain me the behavior of builtin here.
Thanks in advance.

anupam:Markdown$ which [
/usr/bin/[
anupam:Markdown$ echo $?
0
anupam:Markdown$ which test
/usr/bin/test
anupam:Markdown$ echo $?
0
anupam:Markdown$ builtin test
anupam:Markdown$ echo $?
1
anupam:Markdown$ builtin [
-bash: [: missing `]'
anupam:Markdown$ echo $?
2
anupam:Markdown$ 

Best Answer

The [ version of the command requires ] as the mandatory last parameter (so it must be preceded by a space). It’s just a formal, syntactic thing to force users to close the bracketed “block”, so commands look this way:

if [ $1 -eq 2 ]; then

instead of

if [ $1 -eq 2; then

See help [:

$ 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 `['.

Notes

  • The test version does not require nor accept the final ].

  • You don’t need the builtin there. Builtins take priority over external commands, so just [ would execute the builtin. The builtin command is more useful when you have a function or alias masking [.

Related Question