Advertisement

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!

Discussion

If you found a mistake in this article or would like to contribute some content to it, please file an issue in this Git Repository

Disclaimer

The contents of this article are put together to the best of the authors' knowledge, but it cannot be guaranteed that it's always accurate in any environment. It is up to the reader to make sure that all information found in this article, does not do any damage to the reader's working environment or wherever this information is applied to. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, arising from, out of or in connection with this article. Please also note the information given on the Imprint' page.