How can I write a Bash script to install an Apt package for Nginx in a test-driven way?

Let's start with a failing test.

Imagine refactoring a script while using the tests to verify each step. After a few hours, you determine your tests weren't actually checking anything.

I do remember the time I did that. It still hurts.

#!/usr/bin/env bash

# install_package.sh

run_test() {
    exit 1
}

if [ $1 == "test" ]; then
    run_test
fi

Let's run that.

$ ./install_package.sh && echo $?
1

Test is red now - it fails just as it should at this stage.

Let's make it green.

#!/usr/bin/env bash

# install_package.sh

run_test() {
    exit 0
}

if [ $1 == "test" ]; then
    run_test
fi

Run it...

$ ./install_package.sh && echo $?
0

Correct.

Anything to refactor?

Doesn't seem so at the moment!

Let's add a check if Nginx is installed.

It is not, so the test should fail.

#!/usr/bin/env bash

# install_package.sh

run_test() {
    nginx --version > /dev/null
}

if [ $1 == "test" ]; then
    run_test
fi

Run:

$ ./install_package.sh && echo $?
./install_package.sh: line 6: nginx: command not found

The command failed as expected.