5.1 Hello World in Bash
1cd ~/bash 2shellspec
The shellspec command runs a set of tests to confirm that the requirements have been met (these tests are often called ‘acceptance tests’). Later in this course we will look at these tests and how, when, and why to write our own tests.
1Running: /bin/sh [sh] 2F 3 4Examples: 5 1) convert shows greeting 6 When run script bin/convert 7 8 1.1) The output should equal Hello World! 9 10 expected: "Hello World!" 11 got: "" 12 13 # spec/bin/convert_spec.sh:4 14 15 1.2) WARNING: It exits with status non-zero but not found expectation 16 17 status: 2 18 19 # spec/bin/convert_spec.sh:2-5 20 21 1.3) WARNING: There was output to stderr but not found expectation 22 23 stderr: /bin/sh: 0: cannot open bin/convert: No such file 24 25 # spec/bin/convert_spec.sh:2-5 26 27Finished in 0.04 seconds (user 0.03 seconds, sys 0.01 seconds) 281 example, 1 failure 29 30 31Failure examples / Errors: (Listed here affect your suite's status) 32 33shellspec spec/bin/convert_spec.sh:2 # 1) convert shows greeting FAILED
The shellspec tests are currently failing, which should be unsurprising as we have not yet written any code. The output from shellspec may be confusing but don’t worry too much about it at the moment, the main things to notice are on line 28 (telling us we ran one example and had one failure) and line 23 (telling us that the test was trying to run the script bin/convert but it could not since that script does not exist yet).
On line 5 we are told that shellspec was trying to confirm that the convert script ‘shows a greeting’. Line 8 tells us that we are expecting the output to be ‘Hello World!’.
Let’s now write the code to satisfy our requirement.
1mkdir bin 2touch bin/convert 3chmod +x bin/convert
These commands create the convert file and make it an executable (line 3). Now we will edit that file and print out our message.
1vi bin/convert
The vi editor
We are using the vi editor (if you know another editor on Linux feel free to use it instead)—strictly we are using neovim, a more advanced version of vi. vi can be a bit intimidating to new users but is worth learning as it is installed on pretty much all Linux and Unix like systems.
For a full introduction to vi see [Boo22] but I provide a brief guide in Appendix A.
Add the following, single line, to the bin/convert file and save the file.
1echo "Hello World!"
Running bin/convert will print the message ‘Hello World!’ to the screen.
1bin/convert
1Hello World!
If we now run our tests they pass.
1shellspec
1Running: /bin/sh [sh] 2. 3 4Finished in 0.04 seconds (user 0.04 seconds, sys 0.00 seconds) 51 example, 0 failures
The only interesting line in this output is line 5 where we are told we ran one example with no failures.
Congratulations! You are now a coder. You have written a simple script that outputs a message to the screen.
Sure, not the most exciting script in the world, but outputting information to the screen is an essential part of many programs.