The test command is one of the most important commands we have in our shell scripting arsenal. Because shell scripts can often be fragile, especially where user input is concerned, we want to make these as robust as possible. While explaining every aspect of the test command would take a whole chapter, the following are the things test can do:
- Check whether a file exists
- Check whether a directory exists
- Check whether a variable is not empty
- Check whether two variables have the same values
- Check whether FILE1 is older than FILE2
- Check whether INTEGER1 is greater than INTEGER2
And so on and on and on—this should give you at least an impression of things you can check with test. In the Further reading section, we have included an extensive source on test. Make sure to give it a look, as it will definitely help in your shell scripting adventures!
For most scripting and programming languages, there is no such thing as a test command. Obviously, tests are just as important in those languages but, unlike Bash, tests are often directly integrated with the if-then-else logic (which we will discuss in the next part of this chapter). Luckily for us, Bash has a shorthand for the test command, which brings it a lot closer to the syntax of other languages: [ and [[.
Look at the following code to get a better idea of how we can replace the test command with this shorthand:
reader@ubuntu:~/scripts/chapter_09$ vim test-shorthand.sh
reader@ubuntu:~/scripts/chapter_09$ cat test-shorthand.sh
#!/bin/bash
#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-09-29
# Description: Write faster tests with the shorthand!
# Usage: ./test-shorthand.sh
#####################################
# Test if the /tmp/ directory exists using the full command:
test -d /tmp/
test_rc=$?
# Test if the /tmp/ directory exists using the simple shorthand:
[ -d /tmp/ ]
simple_rc=$?
# Test if the /tmp/ directory exists using the extended shorthand:
[[ -d /tmp/ ]]
extended_rc=$?
# Print the results.
echo "The return codes are: ${test_rc}, ${simple_rc}, ${extended_rc}."
reader@ubuntu:~/scripts/chapter_09$ bash test-shorthand.sh
The return codes are: 0, 0, 0.
As you can see, after the plumbing we started with the previously introduced test syntax. Next, we replaced the word test with [, and ended the line with ]. This is the part that Bash has in common with other scripting/programming languages. Note that, unlike most languages, Bash requires a whitespace after [ and before ]! Finally, we used the extended shorthand syntax, starting with [[ and ending with ]]. When we print the return codes, they all return 0, which means that all tests succeeded, even with the different syntaxes.