Automating tests with a Shell script
What you'll learn: How to create a simple Bash script that automatically runs your program against multiple inputs to save time and ensure consistency.
The manual testing bottleneck
Up until now, you have likely tested your code by running ./my_program, typing in a value, and checking if the output looks right. This is fine for a "Hello World" app, but as your projects grow, manual testing becomes a chore. Imagine having to type 20 different inputs every time you change a single line of code!
Think of a Shell script as a tape recorder for your terminal. Instead of typing commands yourself, you record them into a file and play them back instantly.
Creating a test script
A Shell script (usually ending in .sh) is just a list of commands your computer executes in order. In C testing, we use these scripts to feed specific inputs into our program and check the results.
Suppose you have a program called adder that adds two numbers. You can create a file named test.sh like this:
#!/bin/bash
# Run the program with inputs 2 and 3
# The "echo" command pipes the numbers into our C program
echo "2 3" | ./adder > output.txt
# Compare the actual output to what we expected
if grep -q "Result: 5" output.txt; then
echo "Test 1 Passed! (2+3=5)"
else
echo "Test 1 Failed!"
fi
To run this, you would give the script permission with chmod +x test.sh and then type ./test.sh.
Why this matters
The power of this approach is regression testing. As you add complex features to your C project, you might accidentally break a basic feature you wrote weeks ago. If you have a script that runs 50 tests in half a second, you’ll catch that mistake immediately.
By automating the "boring" part of coding, you ensure that your program remains robust without needing to manually re-verify every single feature every time you compile. It transforms testing from a tedious task into a single, satisfying command.
Key takeaway
Automating tests with Shell scripts allows you to run dozens of test cases instantly, ensuring new code changes don't break existing functionality.