1

Recently back to Linux from another operating system I noticed a file called [ which seems strange to me. What is it for?

$ ls -l /usr/bin | head -2
-rwxr-xr-x 1 root root       39552 Nov  3 14:44 [

I'm using Ubuntu 15.04

  • Could you undelete your other question about chmod? It actually has quite an interesting answer even though it isn't doing quite what you thought it was. – Michael Homer Apr 27 '15 at 06:44

2 Answers2

7

The command [ is another "name" for the command test, so that the syntax of if constructs look nicer. These two are equivalent:

if test "$x" -eq 0

if [ "$x" -eq 0 ]

The final ] is only syntactic sugar. The equivalence is mostly just a historic feature.

Note that the newer test construct [[ ... ]] (which is non-standard) is part of the shell syntax, as opposed to being a command.

Kusalananda
  • 333,661
Janis
  • 14,222
0

[ is a command, to ensure you can use type [

It says it's a shell builtin command, or if you use type -a [ you will see that there is another [ under /usr/bin/ directory.

You can see it's help with help [ command.

USAGE: It's another form of if in bash, For example:

[ "Hello" == "Helo" ] ; echo $?

  • That's useful to know but that still doesn't explain why there is a file called [ as well. – Andy Fusniak Apr 27 '15 at 06:34
  • @codemagician: To allow you to run the [ command. – lcd047 Apr 27 '15 at 07:32
  • (a) "It says ...." What says? (b) If it's built into the shell, why is it a file? – TRiG Apr 27 '15 at 08:36
  • @TRIG - (a) "It" refers to type [ as being the shell builtin - (b) type -a [ is the file; they are two different executables – Peter.O Apr 27 '15 at 10:29
  • @Sepahrad Salour - I wouldn't call it another form of if - [ ... ] is a condition tester (generates true/false), whereas if determines which action to perform depending on a true/false value given to it. – Peter.O Apr 27 '15 at 10:40