When programming if you find your self typing something over and over, it’s typically a good indication you need a separate function definition. But what happens when the simple command/function is just too confusing? In programming we typically use MACROS or NAMES for such situations. As far as I know, we don’t have MACROS in shell script but we can define a NAME for something.
Demonstration:
You can split up shell scripts into several files and “include” them into your shell script with the dot (.) command (the dot means ‘include’). Let’s see what that looks like:
_pathname="$(readlink -f "$0")"
_prefix="$(dirname "${_pathname}")"
_include="$(readlink -f "${_prefix}/")"
. "${_include}/api.sh"
As you can see I’ve done a little hoop-jumping to find the location–and hard-locate the actual path–of our script and to do this I’ve used several variables but when I get down to the actual include–the dot–statement, the operation is almost lost. -i.e. when you find yourself reading through the source code of your script, you could very well miss the include part because the operation is just a single dot. Let’s rename the dot command to be something a bit more noticeable.
The easiest way is to use the alias
function.
alias include="."
_pathname="$(readlink -f "$0")"
_prefix="$(dirname "${_pathname}")"
_include="$(readlink -f "${_prefix}/")"
include "${_include}/api.sh"
Well, that looks–and reads–better!
That example was a bit trivial so what happens in a bit more complicated situation? Earlier we defined a function for printing error messages to STDERR called ‘err’. Can we define a name instead of a function?
# err --
# all error messages should be directed to `stderr`.
# EX
# if ! do_something; then
# err "unable to do_something"
# exit 1
# fi
alias err="echo \"[$(date +'%Y-%m-%d %H:%M:%S')] *ERROR*: $*\" >&2"
The above alias will even accept an argument. Pretty cool! Names (aka: alias’), however, have a limitation; names are typically used for single line functions (functions that only preform one operation) but this is typically what names are for. Meaning, names are typically only used in programming to help the readability of your source.
As far as I can tell a alias
used in this way–to define a name–also does not pollute the namespace so if you find out otherwise, please report back here.
Please note: I had hoped these threads would be read more and/or spur some conversation, or generate interest, but that does not appear to be the case so this will be the final thread on shell scripting.