Tests occur on a daily basis in our life, from seeing if you can get up early enough to get to your job to seeing how good you are at passing tests. When you start to do shell programming, tests will be just as important. You want to test files, expressions, variables, strings and more for certain traits. To make this easier, a command was introduced, which we will learn how to use today.
This article comes as an extension of my piece on Control Mechanisms of the UNIX Shell. If you missed it I strongly recommend that you go back and read it, otherwise you will find it a little harder to comprehend this one. In that article I introduced how to use the "if-then-else structure." With this, you could see what is true and what is false inside the UNIX shell.
There are multiple kinds of structures which we can check for some attribute. While we work in the shell, we may have a file, strings, and/or logical expressions composed of commands or numbers. To learn a different function, a method to check its traits for all of this can be time consuming. To reduce the work involved, a command has been introduced a command that covers this. Intuitively enough, the name of the command is: test.
Of course, there are different expressions and options depending on what you want to check. However, these are quite intuitive and make the work much easier. There are two types of accepted syntaxes for the command. The general one:
test expression
Alternatively, you may call it also like this:
[ expression ]
The second version is easier to read, and because of this we use it more often. Nevertheless, if you decide to take advantage of this option you have to make sure that you leave a space before and after the [ and ] characters.