Bash #2 - Functional Command Relay
Posted April 26, 2021 ‐ 2 min read
In software projects, would often appear a 'scripts' directory with various
scripting utilities. The inexperienced bash
scriptwriter would usually
litter up the directory with many execution entry points such as:
Previous post: #1.
build.sh
run.sh
deploy.sh
|
If we would like to clean this up and combines these functions to a single
file, say command.sh
, how one would do so?
A nice way to accomplish this is the following:
#!/bin/bash
# ... common code here ...
|
(for clarification regarding "$@"
, see the previous post regarding execution relay)
I call this method the Functional Command Relay pattern, as it allows execution of each function with the parameters to these functions relayed as-is.
$ ./command.sh build <params>
<output of the original build logic>
|
We can choose how strict we are with the first parameter. For example, by replacing
the last "$@"
line with the following:
|
Worth to mention that the under-utilized function concept in bash
is more
powerful that it may seem at first.
The functions behave like mini-scripts in the same manner that original scripts
would behave, and similar to "real" executable programs that are already
reachable from $PATH
. For instance, it is possible to use echo
for output
and have use functions as components in shell pipes.