This is part thirteen of a series on how to approach bash programming in a way that’s safer and more structured than your basic script.
See part 1 if you want to catch the series from the start.
Last time, we discussed techniques for working in strict mode. This time, let’s TDD a function to implement strict mode.
As a reminder, setting any of the strict mode settings involves calling set -o. In order to unset any of them, you use set +o instead.
This time, let’s start with the tests. We’ll implement our strict_mode function in lib/support.bash.
Before we start with the code, let me tell you how I work iteratively with shpec.
The easiest way to run tests is to have them automatically run when your work is saved. This way you can write the test, see it fail and then see it pass (or fail) as soon as you’ve written your script to disk.
I use a combination of the linux find command along with the entr tool to do so:
entr can be installed on ubuntu with the command sudo apt-get install -y entr.
I run this command in the directory above my lib and shpec directories like so:
entr monitors the files given by find for changes on disk, then runs the shpec command. Because it’s run from the directory above, it sees changes in both the shpec file as well as the script file.
Keeping this in one window while I work in the editor in another lets me see results instantly.
Now the test.
This fails since we don’t yet have strict_mode. Let’s remedy that.
This passes, so on to the next test:
Run shpec and failure again. Good.
Pass. The tests for pipefail and nounset are similar. I don’t bother testing the off setting for the other two.
Here’s the entirety of strict_mode testing in shpec/support_shpec.bash:
And finally, lib/support.bash:
Continue with part 14 - updated outline