Created
March 8, 2018 18:19
-
-
Save niieani/50b8dc262266c52eed44dea8254a1302 to your computer and use it in GitHub Desktop.
Bash Module System
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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})" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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