Being around for a while each of us might have seen the following lines
In the wild it can be found at the beginning of a bash script.
Apparently the script requires an input and fails if the length of the input is zero. If the length is zero it’s not present. Thus the -z
.
The author thought without the input it would make no sense to continue with the execution of script. As a result we exit with a non-zero status (exit 1
).
After a quick search for “bash check if input is provided” we could grab the above straight from Stackoverflow. No further consideration. It’s fine ;)
Hold on! Let’s have fun with the shell.
Regard >
as the prompt and the line which follows afterwards as the output.
Hah. Seems like [
is a command. No if
required.
Check out the manual
Where we find the docs of the -z
argument stating
-z string True if the length of string is zero.
It also states [
is the utility test
. In fact we’re able to interchange [
with test
We can even build an alternative to test
. Formulate the most important requirements into tests. Voila. A home grown testframework which consists of a single function
So && failed
leads to a failure if the command before exits successfully. Which it should not.
And || failed
triggers if the command before exits unsuccessfully. Which again, it should not.
Our quick and dirty implementation in C follows. If we have no input or if the input has a length of zero we exit successfully.
We compile the above
And run the tests
Success!
Copy the compiler output to /usr/local/bin
to reuse it
The script above could now start with
We should not use it in scripts though. Their portability would be destroyed. Only our system will have the assert-empty
utility.
Having a look at the original source of test in C we find it offers a lot more than our assert-empty
. It had time to mature. The commit Initial revision
of the file dates back to November 1992.
Spelunking around the tests
folder of the repository we find how test
is used to test other coreutils, such as rm
.
Check out some cool parts in one of the files used to test rm
We recognize the classic Arrange-Act-Assert.
test
Thus what seemed like an innocent bracket [
helps to make sure the foundations we build upon run smoothly.
Article has been cross-posted on Medium