views:

278

answers:

3

Looking in the gnuwin32/bin directory, there is an odd-looking program file named [.exe

I couldn't find it in the documentation, gnuwin32.sourceforge.net or in a google search, so I ran it and got:

$ [
[: missing `]'
$

so I gave it ] as a parameter and got

$ [ ]

$

It didn't complain, so I assumed it was on the right track. I tried:

$ [ hello ]

again, no complaints. so I tried an arithmetic expression:

$ [ 1 + 1 ]
[: +: binary operator expected
$

I tried a bunch of different combinations, including prefix & postfix notation but nothing seemed to work. What does this thing do?

+6  A: 
test a

==

[ a ]

It's just sugar

Edit: To clarify, that's the conditional syntax, e.g. [ "a" = "a" ]

tusho
+3  A: 

It's used to evaluate conditional expressions.
It is equivalent to (possibly a symlink to?) the test executable.
The manpage is here.

You may see this in a lot of bash scripts:

if [ "$LOGNAME" = "scott" ]
then
    echo "Logged in as Scott"
else
     echo "incorrect user"
fi

The funny thing is, the [ is not part of the bash language, it's actually an executable whose return code is used by the 'IF'. This is the reason why the space after the [ and its first argument is mandatory - if it would be omitted, the script would try to execute ["$LOGNAME" and fail.

You can't do arithmetical operations with it - use expr for that (see here). However, you can test for a wide range of file properties (does it exist? what type is it? etc) as well as use comparison operators on strings and numbers.

Cristi Diaconescu
A: 

Another answer already mentioned it is the same as test. On bash, it is also a builtin, so you can get the help for it with the help builtin (help test).

CesarB