As an alternative to the test command, we can implement the same conditional tests using the single square bracket. Repeating the previous conditional test and omitting the command itself. We will rewrite this, as shown in the following command:
$ [ -f /etc/hosts -a -r /etc/hosts ]
Many times, even as experienced administrators, we are used to language elements and we accept them as they are. I feel many Linux administrators will be surprised to learn that [ is a command for both a shell built-in and a standalone file. Using the type command, we can verify this:
$ type -a [
We can see the output of this command in the following screenshot confirming its existence:
The built-in [ command imitates the test command but it requires a closing bracket.
Now we know a little more about the [ command, which is found in bash and the earlier Bourne shell, we can now continue to add a little command-line list syntax. In addition to the command-line list, we can see the desired functionality working in the following command sample:
$ FILE=/etc/hosts
$ [ -f $FILE -a -r $FILE ] && cat $FILE
Having set the parameter FILE variable, we can test that it is both a regular file and is readable by the user before attempting to list the file contents. In this way, the script becomes more robust without the need for a complex script logic. We can see the code in use in the following screenshot:
This type of abbreviation is quite common and is easily recognizable. We should always be cautious of using abbreviations if they do not add readability. Our aim in scripting should be to write clear and understandable code and avoid shortcuts if they do not add to this goal.