Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

I came across a tweet by Guillermo Rauch. He shared this little snippet.

$ which [

What's that? I rarely do bash scripting so I'm always happy to learn more about it.

Guillermo was also so kind to also share a doc explaining this. If you prefer the TL;DR... here we go:

In bash there is a test command. You can use it to e.g. check if a file exists (with the -e flag) or if a file path points to a directory (with the -d flag). There are also many more options available and you can have a look executing man test. In bash scripts you probably use test inside of an if condition. So how does an if condition looks like in bash?

if test -e /etc/passwd; then
  echo "Alright man..." >&2
  echo "Yuck! Where is it??" >&2
  exit 1

I found the example above online and well... this puzzled me. I always assumed that if conditions have to include [] in bash. And that's my learning today!

It turns out that [] are not bash syntax but an actual bash command.

$ which [

[: shell built-in command

$ man [
TEST(1)                   BSD General Commands Manual                  TEST(1)
     test, [ -- condition evaluation utility

     test expression
     [ expression ]

There are even manual pages for it but you see that the displayed man pages are the man pages of test. So this means that [ and test are actual the same thing. ๐Ÿ˜ฒ

$ test -e /does/not/exist

$ [ -e /does/not/exist ]

Related Topics

Related Articles