Published at
Updated at
Reading time
1min
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 [
/bin/[

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
else
  echo "Yuck! Where is it??" >&2
  exit 1
fi

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)
NAME
     test, [ -- condition evaluation utility

SYNOPSIS
     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
FAIL: 1

$ [ -e /does/not/exist ]
FAIL: 1
Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 1 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles