Now, we know how we can check the exit status of a process to determine if it was successful. However, that is not the only way we can validate the success/failure of commands. For most commands that we run, we could also perform a functional check to see if we were successful. In the previous script, we tried to create the /home/ directory. But what if we were more concerned with the existence of the /home/ directory, instead of the exit status of the process?
The following script shows how we can perform functional checks on the state of our system:
reader@ubuntu:~/scripts/chapter_09$ vim functional-check.sh
reader@ubuntu:~/scripts/chapter_09$ cat functional-check.sh
#!/bin/bash
#####################################
# Author: Sebastiaan Tammer
# Version: v1.0.0
# Date: 2018-09-29
# Description: Introduces functional checks.
# Usage: ./functional-check.sh
#####################################
# Create a directory.
mkdir /tmp/temp_dir
mkdir_rc=$?
# Use test to check if the directory was created.
test -d /tmp/temp_dir
test_rc=$?
# Check out the return codes:
echo "mkdir resulted in ${mkdir_rc}, test resulted in ${test_rc}."
reader@ubuntu:~/scripts/chapter_09$ bash functional-check.sh
mkdir resulted in 0, test resulted in 0.
reader@ubuntu:~/scripts/chapter_09$ bash functional-check.sh
mkdir: cannot create directory ‘/tmp/temp_dir’: File exists
mkdir resulted in 1, test resulted in 0.
We start the preceding script with the usual plumbing. Next, we want to create a directory with mkdir. We grab the exit status and store it in a variable. Next, we use the test command (which we briefly explored in the previous chapter) to validate whether /tmp/temp_dir/ is a directory (and thus, if it was created sometime). We then print the return codes with echo, in the same fashion as we did for return-code.sh.
Next, we run the script twice. Here is where something interesting happens. The first time we run the script, the /tmp/temp_dir/ directory does not exist on the filesystem and is created. Because of this, the exit code for the mkdir command is 0. Since it was successfully created, test -d also succeeds and gives us back an exit status of 0, as expected.
Now, in the second run of the script, the mkdir command does not successfully complete. This is expected, because the first run of the script already created the directory. Since we did not delete it in between the runs, the second run of mkdir is unsuccessful. However, test -d still runs fine: the directory exists, even though it was not created in that run of the script.