[ is an actual bash command
- Published at
- Updated at
- Reading time
- 1min
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
Join 5.5k readers and learn something new every week with Web Weekly.