Click on blue boxes to reveal additional information!
Bash is a ubiquitous scripting language and is used in DevOps environments throughout the world. In many cases, scripting in Bash is required for the sake of transparency, to work closely with the operating system, to allow for quick and easy development, to keep training requirements to a minimum, and to leverage the huge workforce that already knows Bash.
But, code written in Bash is difficult to make reusable. Let's explore why.
What makes Scripts Reusable?
While some think that reusable scripts are just those that contain portions that can copied and pasted into other scripts, this is far from what is really meant by reusable.
Reusable scripts are those that provide public APIs: functions that have well-defined contracts for taking input, generating output, and returning status. Highly reusable code provides general solutions, is more extensible, reduces coupling, and is testable.
Why isn't Scripting Code Reusable?
- Bash has a flat namespace. The variables and functions are all in one namespace. There cannot be more than one function with the same name in a script. And while there is a notion of a
localvariable, it isn't truly local to a function. It is relatively global. The variable is available to the function it is defined in and in all functions ultimately called from the defining function. Due to the way variables work in Bash, the potential for namespace collision is extraordinarily high.
- Bash is not object oriented. Object orientation improves code reuse, recycling, encapsulation, and benefits both design and software maintenance.
- Bash is missing type support. Technically, Bash has no type support. In practice, it provides strings, integers, and one-dimensional associative or positional arrays.
- Bash scripts are typically written as a single file. And while one can use the source command to load functions from another file, this creates requirements for either absolute or relative sourcing of those files. When writing multiple scripts to do related behaviors, this tends to make the process more haphazard and inconsistent.
The result? Script writers take on a throw-away mentality when writing scripts. When script writers attempt to reuse code, they merge separate scripts into a single script. The limitations cited above create the need to do significant refactoring of code to work around these problem areas. In addition, significant thought is needed to identify and merge the data modeling approaches used by the separate scripts when trying to reuse existing code.
In many cases, the unfortunate culmination is that script writers give up on writing reusable code.
Eggsh is designed to solve Bash's limitations and make reusable code writing simple and intuitive.