Skip to content

Instantly share code, notes, and snippets.

@niieani
Created March 8, 2018 18:19
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save niieani/50b8dc262266c52eed44dea8254a1302 to your computer and use it in GitHub Desktop.
Bash Module System
#!/usr/bin/env bash
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
# load our module system:
source "${SCRIPT_DIR}/module.sh"
# below command imports module ./greeter.sh and run its 'greet' function with the following arguments:
module greeter greet tterranigma
module greeter greet niieani
#!/usr/bin/env bash
# this variable is local to this module:
__module__invocationCount=0
# function is "exported" as a part of this module
__module__.greet() {
__module__invocationCount=$((__module__invocationCount+1))
echo Greetings "$@" "(invocation ${__module__invocationCount})"
}
#!/usr/bin/env bash
declare -a __moduleCache=()
module() {
local path="${1}"
local export="${2}"
shift; shift;
local filename
if [[ "${path:0:2}" == "./" ]]
then
filename="$( cd "${BASH_SOURCE[1]%/*}" && pwd )/${path#\./}"
else
# for absolute path we assume it's relative to "SCRIPT_DIR"
filename="${SCRIPT_DIR}/${path}"
fi
load "${filename}.sh" "${export}" "$@"
}
load() {
local filename="${1}"
local export="${2}"
shift; shift;
local moduleName="_moduleId_${filename//[^a-zA-Z0-9]/_}"
local moduleId="${!moduleName}"
if [[ -z "${moduleId}" ]]
then
# module not yet loaded
local moduleId="${#__moduleCache[@]}"
local moduleContents
moduleContents=$(<"${filename}")
local moduleMemberPrefix="__module__${moduleId}"
local prefixedModule="${moduleContents//__module__/$moduleMemberPrefix}"
# declares reference to ID in global scope:
eval ${moduleName}=${moduleId}
__moduleCache+=($moduleName)
# execute the module:
eval "$prefixedModule"
fi
# module already loaded, execute
__module__${moduleId}.${export} "$@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment