30

I was looking at coreutils and found this as one of the files included as part of coreutils: /usr/bin/[. What is [ and what does it do?

It is an executable. I just don't know what it does or how to use it.

$ file /usr/bin/[  
/usr/bin/[: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared  libs), for GNU/Linux 2.6.15, stripped  

When I try to run it, I think it is defaulting to the bash built in line expansion. Instead of actually running the file.

$ "/usr/bin/["
/usr/bin/[: missing ‘]’
$ /usr/bin/\[
/usr/bin/[: missing ‘]’
3
  • 4
  • 3
    man [ works on OS X.
    – Daniel Beck
    Sep 12, 2011 at 17:31
  • 2
    Wow this is incredible. I panicked when I saw this on my system, almost deleted it, as it looks like a file you might have accidentally created (you know like you end up with files called 1 by using >1 instead of >&1 etc... maybe that's just me) I always thought [ was (just) a builtin language thing. Now I'm looking out for /bin/if and /bin/then and /bin/{! Mar 8, 2021 at 9:09

2 Answers 2

37

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?)

2
  • 4
    Note that [ is both a shell built-in and a external program with the same (or similar) usage. In bash, when you run [ or test you are invoking the built-in. Sep 12, 2011 at 7:29
  • It's required because if it were optional the syntax would be ambiguous in certain situations.
    – Random832
    Sep 12, 2011 at 11:57
23

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
1
  • 3
    nice examples of how to use it. "if /usr/bin/["
    – nelaaro
    Sep 12, 2011 at 11:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .