Here is my Katas for creating BASH programs that work. Nothing is new here, butfrom my experience pepole like to abuse BASH, forget computer science and createa Big ball of mud from their programs. Here I provide methods to defend your programs from braking, and keep the codetidy and clean.
Immutable global variables
Try to keep globals to minimum
UPPER_CASE naming
readonly decleration
Use globals to replace cryptic 0,1, etc.
Globals I allways use in my programs:
Everything is local
All variable should be local.
self documenting parameters
Usually for loop use i variable, so it is very important that you declare itas local.
local does not work on global scope.
main()
Help keep all variables local
Intuitive for functional programming
The only global command in the code is: main
Everything is a function
The only code that is running globaly is:
Global declerations that are immutable.
main
Keep code clean
procedures become descriptive
Second example is much better. Finding files is the problem oftemporary_files() and not of main()’s. This code is also testable, by unittesting of temporary_files().
If you try to test the first example, you will mish mash finding temporaryfiles with main algorithm.
As we see, this test does not concern main().
Debugging functions
Run program with -x flag:
debug just a small section of code using set -x and set +x, which will printdebug info just for the current code wrapped with set -x … set +x.
Printing function name and its arguments:
So calling the function:
will print to the standard output:
Code clarity
What this code do?
Let your code speak:
Each line does just one thing
Break expression with back slash \ For example:
Can be written much cleaner:
Symbols at the start of the line indented Bad example of symbols at the end:
Good example where we clearly see the connection between lines and the connecting rods:
Printing usage
Don’t do this:
It should be a function:
echo is repeated in each line. For that we have Here Document:
Pay attention that there should be real tab ‘\t’ in the start of the line for eachline. In vim you can use this replace command if your tab is 4 spaces:
Command line arguments
Here is an example to complement the usage function above. I got this code fromKirk’s blog post - bash shell script to use getopts with gnu style longpositional parameters:
You use it like this, using the immutable ARGS variable we defined at the top:
Unit Testing
very important in higher level languages
Use shunit2 for unit testing
Here is another example using df command:
Here I have exception, for testing, I declare DF in the global scope notreadonly. This is because of shunit2 not allowing to change global scopefunctions.