7.1 Command Line Arguments in Bash
We left off in the Bash version of the program, so let’s pick up there. We want to be able to enter a name by which the program will greet us. If we supply a name on the command line bin/convert "Mark" the program should greet us with Hello Mark!. If no name is supplied on the command line we will expect Hello ! for now (after we learn about controlling a program’s flow (Chapter 9) we will improve our code to do something more sensible).
With new requirements we need new tests. Update your environment.
1exercises 01.02
Run the tests, which we expect to fail as we have not yet written the code.
1shellspec
Sure enough the tests fail.
1Running: /bin/sh [sh] 2FF 3 4Examples: 5 1) convert shows greeting #1 6 When run script bin/convert 7 8 1.1) The output should equal Hello ! 9 10 expected: "Hello !" 11 got: "Hello World!" 12 13 # spec/bin/convert_spec.sh:8 14 15 2) convert shows greeting #2 16 When run script bin/convert Mark 17 18 2.1) The output should equal Hello Mark! 19 20 expected: "Hello Mark!" 21 got: "Hello World!" 22 23 # spec/bin/convert_spec.sh:8 24 25Finished in 0.06 seconds (user 0.05 seconds, sys 0.01 seconds) 262 examples, 2 failures 27 28 29Failure examples / Errors: (Listed here affect your suite's status) 30 31shellspec spec/bin/convert_spec.sh:6 # 1) convert shows greeting #1 FAILED 32shellspec spec/bin/convert_spec.sh:6 # 2) convert shows greeting #2 FAILED
Modify the bin/convert program as follows.
1name="${1}" 2greeting_message="Hello ${name}!" 3echo "${greeting_message}"
Re-run the tests.
The tests now pass. In the program, line 1 assigns the value in variable 1 to a new variable name. In a Bash script variables 1, 2, through 9 are assigned values from arguments supplied on the command line1. Variable 0 is assigned the name of the program being called2. If we invoke our script with bin/convert "Mark" then $1
will be assigned the literal string ‘Mark’.
Why assign this to variable name rather than use it directly? The name 1 does not provide any useful information to someone reading our code. At least not once we use it in our greeting. The only thing greeting_message="Hello ${1}!"
tells us is that the greeting should contain the first argument from the command line, which, while accurate tells us nothing about the program’s intended use for this argument. The
variable name tells us that the author of the program intends this argument to be a name.
A variable name should tell someone reading your code what data it refers to. That is it in a nutshell. There are several heuristics we can use make effective variable names and we will consider these in detail in Appendix B.
As your scripts become more complex you will find that clear variable names become increasingly necessary.