I have used the “Bourne Again Shell” (bash) for years now to automate various tasks. One thing that has bothered me for a long time is not having a good way to test my scripts. Recently, I became aware of “bashunit” while setting up “neovim” as my IDE.
Setup “bashunit”
If you use a Mac with “Homebrew” as your favorite package manager, you can install “bashunit”
with the following brew
command. See the “bashunit”
documentation for other installation options.
brew install bashunit
Writing and running the first test
Writing tests with “bashunit” does not require a complex setup, as the
bashunit
file is self-contained. First, let’s create a sample ”bash’ script.
vim hello-world.sh
#!/bin/bash
function hello_world() {
echo "hello world"
}
hello_world
Next, let’s write our first test with the name given below. I built the
set_up()
function in a way that requires you to name your test files
consistently. If you choose to use a different naming scheme, make sure to
change the set_up()
function accordingly and look for the “bashunit” documentation about naming test files.
For more test examples written with “bashunit” head over to the project’s
documentation at
https://bashunit.typeddevs.com/examples.
- Script file:
hello-world.sh
- Test file:
hello-world_test.sh
vim hello-world_test.sh
#!/bin/bash
function set_up() {
ROOT_DIR="$(dirname "${BASH_SOURCE[0]}")"
FILE_NAME="$(basename "${BASH_SOURCE[0]%_test.sh}").sh"
SCRIPT="${ROOT_DIR}/${FILE_NAME}"
}
function test_hello_world() {
assert_equals "hello world" "$($SCRIPT)"
}
Thanks for reading!