7

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$ 
10

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 [.

  • 2
    @jazzz 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 [. – muru Oct 15 '18 at 7:57
  • 1
    @muru Thank you for your edit and comment. I was not really aware of the help command (not available in Zsh which I use mostly). I’ve just changed my answer to wiki, feel free to include your note directly into the answer. – Melebius Oct 15 '18 at 8:00
  • 2
    @Melebius :O You didn't need to do that! The answer was fine by itself, the edit was just supplementary information (and I could edit without CW anyway :P). Also, zsh user myself, so I added a function just for the times I need to quote help: bh () (bash -c 'for i; do help "$i"; done' bash "$@") – muru Oct 15 '18 at 8:07
  • 1
    For me, test a = a ] complains about having too many arguments. What makes you think test should accept a ]? – hmakholm left over Monica Oct 15 '18 at 12:44
  • 1
    @Melebius: That's not an empty expression; that's an "is ] a non-empty string?" query. – hmakholm left over Monica Oct 15 '18 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.