Test Your Square Brackets

https://news.ycombinator.com/rss Hits: 4
Summary

Test your square brackets! I do shell scripting everyday, and I’m so used to the usage of square brackets when performing some test, that I forgot the whole story. I assume you know that something like the following performs what it seems to do: if [ -f "$file" ]; then echo "The file exists, avoid overwriting it!" exit 2 fi The important part here is the [ ... ] test line. Let’s turn on the DeLorean circuits, and go back in time! test, as it was and it always will be When I was a young, green, university student, I was forced to use test(1) as the only true way to do testing in shell scripting. Therefore, the above snippet of code, was written as follows in my homework: if test -f "$file" then ... fi Yeah, I was also forced to not use semicolons as they were evil (according to my professor, any comment unneeded!). So, what is that test thing after all? I started exploring, and found out that test was a regular command lying somewhere in /usr/bin or /bin (or both, via a link). It’s simple enough to test test (no pun intended!) on a shell command line (i.e., outside a script): % test -d /home/luca % echo $? 0 So far, so good. [ and the modern era Then, while reading a Linux specific book, I found out that it was possible to use the [ ... ] syntax to perform something similar to what I did in C, like if ( ... ), where the parenthesis were substituted by brackets. Digging a little more, I found out that the [ was itself a command, pretty much as test. Then, doing a ls -l I discovered that test and [ were much more than similar programs, they were the same program: % ls -l '/bin/test' '/bin/[' -r-xr-xr-x 2 root wheel 12184 Jun 6 2025 /bin/[ -r-xr-xr-x 2 root wheel 12184 Jun 6 2025 /bin/test % sha1sum '/bin/test' '/bin/[' 623e9bbe1784ebf1c8fb5d404978e7ffb7b1ef7b /bin/test 623e9bbe1784ebf1c8fb5d404978e7ffb7b1ef7b /bin/[ Therefore, when placing a [ into my scripts, I was silently calling test. Understanding the closing bracket So, after having discovered that [ was just an ...

First seen: 2026-01-15 12:16

Last seen: 2026-01-15 15:17