As a little bonus, we have a slight improvement for the test-shorthand.sh script. In the previous chapter, we explained that, if we have to use the same value multiple times in a script, we're better off making it a variable. If the value of the variable does not change during the script's execution and is not influenced by user input, we use a CONSTANT. Take a look at how we would incorporate that in our previous script:
reader@ubuntu:~/scripts/chapter_09$ cp test-shorthand.sh test-shorthand-variable.sh
reader@ubuntu:~/scripts/chapter_09$ vim test-shorthand-variable.sh
reader@ubuntu:~/scripts/chapter_09$ cat test-shorthand-variable.sh
#!/bin/bash
#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-09-29
# Description: Write faster tests with the shorthand, now even better
# with a CONSTANT!
# Usage: ./test-shorthand-variable.sh
#####################################
DIRECTORY=/tmp/
# Test if the /tmp/ directory exists using the full command:
test -d ${DIRECTORY}
test_rc=$?
# Test if the /tmp/ directory exists using the simple shorthand:
[ -d ${DIRECTORY} ]
simple_rc=$?
# Test if the /tmp/ directory exists using the extended shorthand:
[[ -d ${DIRECTORY} ]]
extended_rc=$?
# Print the results.
echo "The return codes are: ${test_rc}, ${simple_rc}, ${extended_rc}."
reader@ubuntu:~/scripts/chapter_09$ bash test-shorthand-variable.sh
The return codes are: 0, 0, 0.
While the end result is the same, this script is more robust if we ever want to change it. Furthermore, it shows us that we can use variables in the test shorthand, which will automatically be expanded by Bash.