What is /usr/bin/[ and how do I use it?

Solution 1:

It's an equivalent of the command test. (See info test.) Generally you use it in scripts in conditional expressions like:

if [ -n "$1" ]; then
    echo $1
fi

The closing bracket is required to enclose the conditional. (Well, it looks like its required just to look nicer in the code. Does anybody know any other practical reason for it?)

Solution 2:

It is equivalent to the test command.

Instead of

if /usr/bin/test -z "$VAR"
then
    echo VAR not set
fi

You can use:

if /usr/bin/[ -z "$VAR" ]
then
    echo VAR not set
fi

It can be used in loops too:

i=0
while [ $i -lt 10 ]
do
   echo $i
   ((i++))
done

You can also use them in one-liners like this:

[ -z "$VAR" ] && echo VAR not set && exit

[ -f foo.txt ] && cat foo.txt